package com.moka.gdtauto.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.service.SysUserService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * 登录令牌拦截器
 * 验证用户登录令牌是否有效
 * 
 * @author moka
 * @since 2026-02-09
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginTokenInterceptor implements HandlerInterceptor {

    private final SysUserService sysUserService;

    private static final String[] IGNORE_URI = {
        "/api/user/login", 
        "/api/user/user-token-callback",
        "/api/gdt/auth/callback", 
        "/health",
        "/mcp/**"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取登录令牌
        String loginToken = request.getHeader("X-Login-Token");
        
        // 登录接口不需要验证令牌
        String requestURI = request.getRequestURI();
        for (String uri : IGNORE_URI) {
            // AntPathMatcher
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            if (antPathMatcher.match(uri, requestURI)) {
                return true;    
            }
        }
        
        // 如果没有令牌，返回401
        if (loginToken == null || loginToken.isEmpty()) {
            log.warn("请求未携带登录令牌，URI={}", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\"}");
            return false;
        }
        
        // 验证令牌
        SysUser user = sysUserService.getByLoginToken(loginToken);
        if (user == null) {
            log.warn("登录令牌无效或已过期，token={}", loginToken.substring(0, 8) + "...");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"登录已过期，请重新登录\"}");
            return false;
        }
        
        // 将用户信息设置到请求属性中，供后续使用
        request.setAttribute("auth-user", user);
        
        return true;
    }
}
