package com.luojia_channel.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.luojia_channel.common.domain.Result;
import com.luojia_channel.common.domain.UserDTO;
import com.luojia_channel.common.exception.UserException;
import com.luojia_channel.common.utils.JWTUtil;
import com.luojia_channel.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private final JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求中的双Token
        String accessToken = request.getHeader("Authorization");
        String refreshToken = request.getHeader("X-Refresh-Token");
        try {
            // 验证Token并处理自动刷新
            UserDTO user = jwtUtil.checkLogin(accessToken, refreshToken);
            // 将新Token写入响应头
            if (user.getAccessToken() != null) {
                response.setHeader("New-Access-Token", JWTUtil.TOKEN_PREFIX + user.getAccessToken());
                response.setHeader("New-Refresh-Token", user.getRefreshToken());
            }
            // 将用户信息存入请求上下文
            UserContext.setUser(user);
            return true;
        } catch (UserException ex) {
            // Token验证失败处理
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(
                    JSON.toJSONString(Result.fail(ex.getMessage()))
            );
            return false;
        }
    }
}
