package com.example.demo.security;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtils;
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.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    private final JwtUtils jwtUtils;
    private final UserService userService;

    public JwtAuthenticationFilter(JwtUtils jwtUtils, UserService userService) {
        this.jwtUtils = jwtUtils;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        logger.debug("JWT过滤器处理请求: {}", request.getRequestURI());
        
        try {
            String authHeader = request.getHeader("Authorization");
            logger.debug("Authorization头: {}", authHeader);
            
            String token = jwtUtils.extractTokenFromHeader(authHeader);
            logger.debug("提取的token: {}", token != null ? "存在" : "不存在");

            if (token != null) {
                String username = jwtUtils.getUsernameFromToken(token);
                logger.debug("从token获取用户名: {}", username);
                
                if (username != null && jwtUtils.validateToken(token, username)) {
                    User user = userService.findByUsername(username);
                    logger.debug("查找用户: {}", user != null ? user.getUsername() : "未找到");
                    
                    if (user != null) {
                        // 创建用户权限列表
                        List<GrantedAuthority> authorities = new ArrayList<>();
                        authorities.add(new SimpleGrantedAuthority(user.getRole()));
                        
                        UsernamePasswordAuthenticationToken authToken = 
                            new UsernamePasswordAuthenticationToken(user, null, authorities);
                        authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authToken);
                        logger.debug("JWT认证成功，用户: {}, 角色: {}", username, user.getRole());
                    } else {
                        logger.warn("JWT中的用户不存在: {}", username);
                    }
                } else {
                    logger.debug("JWT验证失败，用户: {}", username);
                }
            } else {
                logger.debug("没有token");
            }
        } catch (Exception e) {
            logger.error("JWT认证过程中发生异常: {}", e.getMessage(), e);
            // 清除可能存在的认证信息
            SecurityContextHolder.clearContext();
        }

        filterChain.doFilter(request, response);
    }
}
