package com.zsElectric.boot.common.util.electric.queryToken;

import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class ThirdPartyJwtAuthFilter extends OncePerRequestFilter {

    @Resource
    private JwtTokenUtil jwtTokenUtil; // 你的JWT工具类
    @Resource
    private JwtAuthenticationEntryPoint authenticationEntryPoint; // 统一认证异常处理

    // 定义你的第三方接口路径模式，例如 /api/third-party/**
    private final List<String> thirdPartyApiPaths = Arrays.asList(
            "/charge-business/v1/linkData/notification_start_charge_result",
            "/charge-business/v1/linkData/notification_equip_charge_status",
            "/charge-business/v1/linkData/notification_stop_charge_result",
            "/charge-business/v1/linkData/notification_charge_order_info",
            "/charge-business/v1/linkData/notification_stationStatus"
    );
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    public ThirdPartyJwtAuthFilter() {
        log.warn("========== ThirdPartyJwtAuthFilter 已初始化 ==========");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        
        String requestUri = request.getRequestURI();
        log.warn("第三方JWT过滤器处理请求: {}", requestUri);

        boolean isThirdPartyRequest = thirdPartyApiPaths.stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, requestUri));

        // 检查当前请求是否是需要第三方Token验证的接口
        if (isThirdPartyRequest) {
            log.warn("检测到第三方接口请求: {}", requestUri);
            String token = extractToken(request);
            
            if (token == null) {
                log.error("Token缺失，请求URI: {}", requestUri);
                // Token缺失，通过AuthenticationEntryPoint返回统一错误格式
                authenticationEntryPoint.commence(request, response, 
                    new AuthenticationServiceException("Missing or invalid Bearer token"));
                return; // 重要：直接返回，不再执行过滤链后续操作
            }
            
            log.warn("提取到Token: {}...", token.substring(0, Math.min(20, token.length())));
            
            try {
                // 验证Token的有效性（例如是否过期、签名是否正确）
                if (jwtTokenUtil.validateToken(token)) {
                    // 从Token中解析用户标识
                    String principal = jwtTokenUtil.getOperatorIdFromToken(token);
                    log.warn("Token验证成功，OperatorID: {}", principal);
                    // 构建Authentication对象，细节见下文
                    UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(principal, null, new ArrayList<>());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 将认证信息设置到SecurityContext中[5](@ref)
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                } else {
                    log.error("Token验证失败，Token: {}...", token.substring(0, Math.min(20, token.length())));
                    // Token无效
                    authenticationEntryPoint.commence(request, response, 
                        new AuthenticationServiceException("Invalid token"));
                    return;
                }
            } catch (Exception e) { // 捕获JWT解析等特定异常
                log.error("Token验证异常: {}", e.getMessage(), e);
                authenticationEntryPoint.commence(request, response, 
                    new AuthenticationServiceException("Token validation failed: " + e.getMessage()));
                return;
            }
        } else {
            log.debug("非第三方接口请求，跳过Token验证: {}", requestUri);
        }
        
        // 如果不是第三方接口，或者Token验证通过，则继续执行后续过滤器
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头Authorization中提取Bearer Token[4,5](@ref)
     */
    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }
}