package com.huimv.employment.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huimv.employment.common.exception.ErrorCode;
import com.huimv.employment.common.web.R;
import com.huimv.employment.service.config.InternalApiProperties;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * MCP 接口鉴权：保护 {@code /api/mcp/**}。
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class McpAuthFilter extends OncePerRequestFilter {

    private static final String HEADER_AI_KEY = "X-Fe-Ai-Key";

    private final InternalApiProperties internalApiProperties;
    private final ObjectMapper objectMapper;

    public McpAuthFilter(InternalApiProperties internalApiProperties, ObjectMapper objectMapper) {
        this.internalApiProperties = internalApiProperties;
        this.objectMapper = objectMapper;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        if (path == null) {
            return true;
        }
        return path == null || !path.startsWith("/api/mcp/");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        if (!internalApiProperties.isEnabled()) {
            writeError(response, ErrorCode.INTERNAL_API_DISABLED);
            return;
        }
        if (internalApiProperties.requiresAiKey()) {
            String providedKey = request.getHeader(HEADER_AI_KEY);
            if (!internalApiProperties.getAiKey().equals(providedKey)) {
                writeError(response, ErrorCode.INTERNAL_API_UNAUTHORIZED);
                return;
            }
        }
        if (internalApiProperties.hasIpRestriction()) {
            String clientIp = resolveClientIp(request);
            if (!internalApiProperties.isAllowedIp(clientIp)) {
                writeError(response, ErrorCode.FORBIDDEN);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private String resolveClientIp(HttpServletRequest request) {
        String forwarded = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(forwarded)) {
            int commaIndex = forwarded.indexOf(',');
            return commaIndex > 0 ? forwarded.substring(0, commaIndex).trim() : forwarded.trim();
        }
        return request.getRemoteAddr();
    }

    private void writeError(HttpServletResponse response, ErrorCode errorCode) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(objectMapper.writeValueAsString(R.fail(errorCode.getCode(), errorCode.getMessage())));
    }
}
