package com.zhentao.security;

import com.zhentao.service.AuthService;
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 javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 从请求头中提取Token，验证并设置认证信息
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private AdminUserDetailsService adminUserDetailsService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取Token
        String token = getTokenFromRequest(request);
        
        if (token != null) {
            try {
                // 从Token获取用户信息
                com.zhentao.entity.AdminUser adminUser = authService.getUserByToken(token);
                
                if (adminUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 加载用户详情（包含权限信息）
                    AdminUserDetails userDetails = (AdminUserDetails) adminUserDetailsService.loadUserById(adminUser.getId());
                    
                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    null,
                                    userDetails.getAuthorities()
                            );
                    
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 设置到Security上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (Exception e) {
                logger.error("无法设置用户认证", e);
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    /**
     * 从请求中提取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        // 兼容不带Bearer前缀的Token
        if (bearerToken != null && !bearerToken.isEmpty()) {
            return bearerToken;
        }
        return null;
    }
}

