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;

/**
 * 管理员认证拦截器
 * 
 * @author emotion-museum
 * @date 2025-10-27
 */
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AdminAuthInterceptor.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("管理员拦截器处理请求: {} {}", method, requestURI);

        if ("OPTIONS".equals(method)) {
            return true;
        }

        if (isPublicAdminEndpoint(requestURI)) {
            log.debug("管理员公开接口，无需认证: {}", requestURI);
            return true;
        }

        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;
        }

        String token = authHeader.substring(7);
        
        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;
        }

        String userType = jwtUtil.getUserTypeFromToken(token);
        if (!"admin".equals(userType)) {
            log.warn("非管理员用户尝试访问管理员接口: {}, userType={}", requestURI, userType);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":403,\"message\":\"无权限访问\",\"data\":null}");
            return false;
        }

        String adminId = jwtUtil.getUserIdFromToken(token);
        String username = jwtUtil.getUsernameFromToken(token);

        request.setAttribute("adminId", adminId);
        request.setAttribute("username", username);
        request.setAttribute("token", token);
        request.setAttribute("userType", "admin");

        UserContextHolder.setCurrentUserId(adminId);
        UserContextHolder.setCurrentUsername(username);
        UserContextHolder.setCurrentToken(token);

        log.debug("管理员Token验证成功，管理员: {} ({})", username, adminId);
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.clear();
        log.debug("管理员请求完成，已清除用户上下文");
    }

    /**
     * 判断是否为管理员公开接口（不需要认证）
     */
    private boolean isPublicAdminEndpoint(String requestURI) {
        String[] publicEndpoints = {
            "/admin/auth/login",
            "/admin/auth/refreshToken",
            "/api/admin/auth/login",  // 包含context-path的路径
            "/api/admin/auth/refreshToken"  // 包含context-path的路径
        };

        for (String endpoint : publicEndpoints) {
            if (requestURI.equals(endpoint) || requestURI.endsWith(endpoint)) {
                return true;
            }
        }

        return false;
    }
}
