package top.awinx.stu01.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import top.awinx.stu01.common.Result;
import top.awinx.stu01.config.JwtConfig;
import top.awinx.stu01.utils.JwtUtil;

import java.io.PrintWriter;

/**
 * JWT拦截器：校验请求头中的token合法性
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private JwtConfig jwtConfig;

    /**
     * 预处理：请求到达Controller前校验token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头中的token
        String token = request.getHeader(jwtConfig.getHeader());
        String prefix = jwtConfig.getPrefix();
        if (token != null && token.startsWith(prefix)) {
            token = token.substring(prefix.length());
            token = token.trim();
        }

        // 2. 校验token是否存在且合法
        if (token == null || !jwtUtil.validateToken(token)) {
            // 3. 非法token/无token，返回400错误
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            Result<Object> result = Result.error("请先登录或token已过期");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(result));
            writer.flush();
            writer.close();
            return false; // 拦截请求
        }

        // 4. token合法，放行请求
        return true;
    }
}
