package kr.co.accura.wbx.spring.auth;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {

    private final JwtProvider jwtProvider;

    @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 {
                Claims claims = jwtProvider.parseToken(token);

                // MFA 토큰은 인증 불가
                if (jwtProvider.isMfaToken(claims)) {
                    chain.doFilter(request, response);
                    return;
                }

                Long userId = claims.get("user_id", Long.class);
                String email = claims.get("email", String.class);
                String username = claims.get("username", String.class);
                String fullName = claims.get("full_name", String.class);
                Boolean isAdmin = claims.get("is_admin", Boolean.class);
                Long deptId = claims.get("department_id", Long.class);

                @SuppressWarnings("unchecked")
                List<String> roles = claims.get("roles", List.class);

                WbxUserDetails user = WbxUserDetails.builder()
                        .id(userId)
                        .email(email != null ? email : "")
                        .username(username != null ? username : "")
                        .fullName(fullName != null ? fullName : "")
                        .isAdmin(Boolean.TRUE.equals(isAdmin))
                        .departmentId(deptId)
                        .roles(roles != null ? roles : List.of())
                        .build();

                var auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            } catch (Exception e) {
                log.debug("JWT validation failed: {}", e.getMessage());
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        return path.contains("/auth/login") || path.contains("/auth/sso")
                || path.equals("/health") || path.startsWith("/actuator");
    }
}
