package com.example.sjkbf.config;

import com.example.sjkbf.util.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 
        throws ServletException, IOException {


        // 1. 从请求头获取 Token
        String token = jwtTokenUtil.getTokenFromRequest(request);
        try {
            // 2. Token 存在且有效（基础验证：签名、过期时间）
            if (token != null && jwtTokenUtil.validateToken(token)) {
                // 3. 直接从 Token 中解析用户信息和权限（无需查库）
                String username = jwtTokenUtil.getUsernameFromToken(token);
                List<GrantedAuthority> authorities = jwtTokenUtil.getAuthoritiesFromToken(token)
                        .stream()
                        .map(SimpleGrantedAuthority ::new)
                        .collect(Collectors.toList());

                // 4. 构建 Authentication 对象（权限来自 Token）
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(
                                username, // 主体可以是用户名（或自定义 User 对象）
                                null,     // 凭证（密码）无需存储
                                authorities
                        );

                // 5. 存入 SecurityContext（后续鉴权直接使用 Token 中的权限）
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }catch (JwtException e){
            sendErrorResponse(response, 4011, "请重新登录");
            return;
        }
        catch (Exception e) {
            // Token 解析失败（如篡改、过期），清理上下文
            SecurityContextHolder.clearContext();
            sendErrorResponse(response, 4013, "认证失败");
            logger.error("认证失败：" + e.getMessage());
            return;
        }

        // 6. 继续过滤器链
        chain.doFilter(request, response);
    }


    // 发送 JSON 错误响应
    private void sendErrorResponse(HttpServletResponse response, int code, String message)
            throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");

        Map<String, Object> errorData = new HashMap<>();
        errorData.put("code", code);
        errorData.put("msg", message);

        response.getWriter().write(new ObjectMapper().writeValueAsString(errorData));
    }
}