package com.mosquito.project.web;

import com.mosquito.project.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserAuthInterceptor implements HandlerInterceptor {

    private final AuthService authService;

    public UserAuthInterceptor(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authorization == null || authorization.isBlank()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        AuthService.TokenInfo tokenInfo = authService.validateToken(authorization);
        if (tokenInfo == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 获取用户信息并设置到request属性中
        AuthService.UserInfo user = authService.getUserById(tokenInfo.userId);
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        request.setAttribute("userId", tokenInfo.userId);
        request.setAttribute("username", user.username);
        request.setAttribute("displayName", user.displayName);
        request.setAttribute("departmentId", user.departmentId);
        request.setAttribute("roles", user.roles);
        request.setAttribute("permissions", user.permissions);
        return true;
    }
}
