package com.vibevault.security;

import com.vibevault.model.User;
import com.vibevault.repository.UserRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.Collections;
import java.util.List;

/**
 * JWT 认证过滤器
 * 
 * 需要实现：
 * - 从请求头中提取 Authorization: Bearer <token>
 * - 验证 token 有效性
 * - 如果有效，将用户信息设置到 SecurityContext 中
 * - [Challenge] 从数据库中读取用户角色并设置到 Authentication 中
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final UserRepository userRepository;

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

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        
        // 1. 从请求头获取 Authorization
        String authHeader = request.getHeader("Authorization");
        
        // 2. 检查是否以 "Bearer " 开头
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 3. 提取 token
        String token = authHeader.substring(7);
        
        // 4. 从 token 中提取用户名
        String username;
        try {
            username = jwtService.extractUsername(token);
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 5. 检查用户是否已经认证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 6. 从数据库中查找用户
            User user = userRepository.findByUsername(username)
                    .orElse(null);
            
            // 7. 验证 token
            if (user != null && jwtService.isTokenValid(token, username)) {
                // 8. 创建 Authentication 对象，包含用户角色
                List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                        new SimpleGrantedAuthority(user.getRole())
                );
                
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        authorities
                );
                
                // 9. 设置认证详情
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                // 10. 设置到 SecurityContextHolder
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        
        filterChain.doFilter(request, response);
    }
}
