package org.lingniu.sdk.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lingniu.sdk.model.token.AccessTokenInfo;
import org.lingniu.sdk.service.TokenService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class IdpAuthenticationFilter extends OncePerRequestFilter {
    private final TokenService tokenService;
    
    public IdpAuthenticationFilter(TokenService tokenService) {
        this.tokenService = tokenService;
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {

        try {
            AccessTokenInfo accessTokenInfo = null;
            // 验证令牌
            if (tokenService.validateAccessToken(request)) {
                accessTokenInfo = tokenService.getAccessTokenInfo(request);
            }else{
                accessTokenInfo = tokenService.refreshToken(request, response);
            }
            if(accessTokenInfo!=null){
                // 创建认证对象
                OAuth2AuthenticationToken authentication =
                        new OAuth2AuthenticationToken(
                                tokenService.convertPrincipal(accessTokenInfo),null,accessTokenInfo.getClientRegistrationId()
                        );

                // 设置认证信息到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        } catch (Exception e) {
            // 令牌验证失败，记录日志但不中断请求
            logger.error("token 验证失败", e);
        }
        
        filterChain.doFilter(request, response);
    }

}