package cn.nianxx.thhotel.platform.security.service.impl;

import cn.nianxx.thhotel.platform.identity.service.AuthService;
import cn.nianxx.thhotel.platform.security.common.dto.AuthenticatedUserContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 可选登录态过滤器。只负责解析 Bearer token 并注入上下文，不强制拦截现有业务接口。
 */
@Component
public class OptionalAuthTokenFilter extends OncePerRequestFilter {

    private final AuthService authService;

    /**
     * 注入登录认证服务，过滤器只做可选 token 解析。
     */
    public OptionalAuthTokenFilter(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 每个请求尝试解析 Bearer token；失败时保持兼容，不直接返回 401。
     */
    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        try {
            Optional<AuthenticatedUserContext> context = authService.resolveOptionalContext(
                    request.getHeader("Authorization"));
            context.ifPresent(CurrentUserContextHolder::set);
            filterChain.doFilter(request, response);
        } finally {
            CurrentUserContextHolder.clear();
        }
    }
}
