package com.zioinfo.kintex.auth;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * Bearer JWT → SecurityContext 인증 세팅. 토큰이 없거나 유효하지 않으면 인증 미설정(익명)으로 통과시키고,
 * 실제 접근 제어는 SecurityConfig(인증 필요 경로)와 각 컨트롤러의 행사 RBAC 가드가 담당한다.
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;

    public JwtAuthenticationFilter(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            try {
                KintexPrincipal principal = jwtService.verify(token);
                var authority = new SimpleGrantedAuthority(
                        principal.hallManager() ? "ROLE_HALL_MANAGER" : "ROLE_USER");
                var auth = new UsernamePasswordAuthenticationToken(
                        principal, null, List.of(authority));
                SecurityContextHolder.getContext().setAuthentication(auth);
            } catch (Exception ignored) {
                // 유효하지 않은 토큰 → 익명 통과. 보호 경로에서 401 처리.
                SecurityContextHolder.clearContext();
            }
        }
        chain.doFilter(request, response);
    }
}
