package com.mosquito.project.web;

import com.mosquito.project.security.IntrospectionResponse;
import com.mosquito.project.security.UserIntrospectionService;
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 UserIntrospectionService introspectionService;

    public UserAuthInterceptor(UserIntrospectionService introspectionService) {
        this.introspectionService = introspectionService;
    }

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

        IntrospectionResponse result = introspectionService.introspect(authorization);
        if (!result.isActive()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        request.setAttribute("userId", result.getUserId());
        request.setAttribute("tenantId", result.getTenantId());
        request.setAttribute("roles", result.getRoles());
        request.setAttribute("scopes", result.getScopes());
        request.setAttribute("tokenId", result.getJti());
        request.setAttribute("tokenExp", result.getExp());
        return true;
    }
}
