package org.xyzh.auth.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.xyzh.auth.service.UserDetailsServiceImpl;
import org.xyzh.auth.util.JwtTokenUtil;
import org.xyzh.auth.config.AuthProperties;

import java.io.IOException;

/**
 * @description    JwtAuthenticationFilter.java文件描述 JWT认证过滤器
 * @filename    JwtAuthenticationFilter.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthProperties authProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String requestURI = request.getRequestURI();
        
        // 检查是否在白名单中
        if (isWhitelisted(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = getTokenFromRequest(request);
        
        if (StringUtils.hasText(token)) {
            try {
                String userId = jwtTokenUtil.getUserIdFromToken(token);
                
                if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUserId(userId);
                    
                    if (jwtTokenUtil.validateToken(token, userId)) {
                        UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            } catch (Exception e) {
                logger.error("JWT token validation failed: " + e.getMessage());
            }
        }

        filterChain.doFilter(request, response);
    }

    /**
     * @description    从请求中获取Token
     * @param    request HTTP请求
     * @return    String Token
     * @author    yslg
     * @since 2025-09-28
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * @description    检查请求路径是否在白名单中
     * @param    requestURI 请求URI
     * @return    boolean 是否在白名单中
     * @author    yslg
     * @since 2025-09-28
     */
    private boolean isWhitelisted(String requestURI) {
        return authProperties.getWhiteList().stream()
                .anyMatch(whitePath -> requestURI.matches(whitePath.replace("*", ".*")));
    }
}
