package com.cameleer.server.app.web;

import com.cameleer.server.core.runtime.Environment;
import com.cameleer.server.core.runtime.EnvironmentRepository;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.HandlerMapping;

import java.util.Map;

/**
 * Resolves the {@code {envSlug}} path variable into an {@link Environment} for handlers
 * annotated with {@link EnvPath}. Validates the slug exists in the repository and rejects
 * unknown slugs with 404.
 * <p>
 * Paired with {@code SecurityConfig} role rules, this guarantees every env-scoped data
 * endpoint receives a real, authorized env without per-handler boilerplate.
 */
@Component
public class EnvironmentPathResolver implements HandlerMethodArgumentResolver {

    static final String ENV_SLUG_VARIABLE = "envSlug";

    private final EnvironmentRepository environments;

    public EnvironmentPathResolver(EnvironmentRepository environments) {
        this.environments = environments;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(EnvPath.class)
                && Environment.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest request,
                                  WebDataBinderFactory binderFactory) {
        @SuppressWarnings("unchecked")
        Map<String, String> vars = (Map<String, String>) request.getAttribute(
                HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
                RequestAttributes.SCOPE_REQUEST);
        String slug = vars != null ? vars.get(ENV_SLUG_VARIABLE) : null;
        if (slug == null || slug.isBlank()) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
                    "Handler uses @EnvPath but path has no {envSlug} variable");
        }
        return environments.findBySlug(slug)
                .orElseThrow(() -> new ResponseStatusException(
                        HttpStatus.NOT_FOUND, "Unknown environment: " + slug));
    }
}
