package com.emotion.interceptor;

import com.emotion.util.JwtUtil;
import com.emotion.util.UserContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 * 
 * @author huazhongmin
 * @date 2025-07-23
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthInterceptor.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        
        log.debug("JWT拦截器处理请求: {} {}", method, requestURI);

        // 跨域预检请求直接放行
        if ("OPTIONS".equals(method)) {
            return true;
        }

        // 不需要认证的接口
        if (isPublicEndpoint(requestURI)) {
            log.debug("公开接口，无需认证: {}", requestURI);
            return true;
        }

        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("请求缺少Authorization头或格式错误: {}", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\",\"data\":null}");
            return false;
        }

        // 提取token
        String token = authHeader.substring(7);
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            log.warn("Token验证失败: {}", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\",\"data\":null}");
            return false;
        }

        // 从token中获取用户信息并设置到请求属性和上下文中
        String userId = jwtUtil.getUserIdFromToken(token);
        String username = jwtUtil.getUsernameFromToken(token);

        // 设置到请求属性中（兼容现有代码）
        request.setAttribute("userId", userId);
        request.setAttribute("username", username);
        request.setAttribute("token", token);

        // 设置到线程本地上下文中（推荐使用）
        UserContextHolder.setCurrentUserId(userId);
        UserContextHolder.setCurrentUsername(username);
        UserContextHolder.setCurrentToken(token);

        log.debug("Token验证成功，用户: {} ({})", username, userId);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除用户上下文，防止内存泄漏
        UserContextHolder.clear();
        log.debug("请求完成，已清除用户上下文");
    }

    /**
     * 判断是否为公开接口（不需要认证）
     */
    private boolean isPublicEndpoint(String requestURI) {
        // 公开接口列表
        String[] publicEndpoints = {
            "/api/auth/login",
            "/api/auth/register",
            "/api/auth/captcha",
            "/api/auth/refresh-token",
            "/api/health",
                "/api/ws/chat",
                    "/swagger-ui",
            "/v3/api-docs",
            "/actuator"
        };

        for (String endpoint : publicEndpoints) {
            if (requestURI.startsWith(endpoint)) {
                return true;
            }
        }

        return false;
    }
}
