package com.lesingle.creation.common.filter;

import com.lesingle.creation.common.config.JwtProperties;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.common.util.JwtTokenUtil;
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.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT 认证过滤器
 *
 * @author lesingle
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;
    private final UserDetailsService userDetailsService;
    private final JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取 Token
        String token = getTokenFromRequest(request);

        if (StringUtils.hasText(token)) {
            try {
                // 验证 Token
                String username = jwtTokenUtil.getUsernameFromToken(token);

                if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 从数据库加载用户信息（UserDetailsServiceImpl 返回的是 UserPrincipal）
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    // 验证 Token 是否有效
                    if (jwtTokenUtil.isTokenValid(token, userDetails)) {
                        // 创建认证对象（principal 使用 UserPrincipal 类型）
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(
                                    userDetails,  // 这就是 UserPrincipal 类型
                                    null,
                                    userDetails.getAuthorities()
                                );
                        authentication.setDetails(
                            new WebAuthenticationDetailsSource().buildDetails(request)
                        );
                        // 设置到 SecurityContext
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.debug("用户认证成功：{}, userId={}",
                            userDetails.getUsername(),
                            userDetails instanceof UserPrincipal ? ((UserPrincipal) userDetails).getUserId() : "unknown");
                    }
                }
            } catch (Exception e) {
                log.warn("Token 验证失败：{}", e.getMessage());
            }
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头中获取 Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(jwtProperties.getHeader());
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(jwtProperties.getTokenPrefix())) {
            return bearerToken.substring(jwtProperties.getTokenPrefix().length()).trim();
        }
        // 也支持 token 作为查询参数
        String token = request.getParameter("token");
        if (StringUtils.hasText(token)) {
            return token;
        }
        return null;
    }
}
