package org.xyzh.gateway.filter;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.xyzh.common.auth.config.AuthProperties;
import org.xyzh.common.auth.contants.AuthContants;
import org.xyzh.common.auth.token.TokenParser;
import org.xyzh.common.core.domain.ResultDomain;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @description Gateway 全局认证过滤器 - 用于验证 JWT Token
 * @author yslg
 * @since 2025-12-02
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Autowired
    private TokenParser tokenParser;

    @Autowired
    private AuthProperties authProperties;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        log.debug("Gateway 请求路径: {}", path);

        // 1. 检查认证功能是否启用
        if (!authProperties.isEnabled()) {
            log.debug("认证功能未启用，直接放行");
            return chain.filter(exchange);
        }

        // 2. 检查是否在白名单中
        if (isWhitelisted(path)) {
            log.debug("路径在白名单中，跳过认证: {}", path);
            return chain.filter(exchange);
        }

        // 3. 提取 Token
        String token = extractToken(request);
        if (!StringUtils.hasText(token)) {
            log.warn("请求缺少 Token: {}", path);
            return unauthorizedResponse(exchange, "未提供认证令牌，请先登录");
        }

        try {
            // 4. 验证 Token
            if (tokenParser.isTokenExpired(token)) {
                log.warn("Token 已过期: {}", path);
                return unauthorizedResponse(exchange, "认证令牌已过期，请重新登录");
            }

            // 5. 获取用户信息
            String userId = tokenParser.getUserIdFromToken(token);
            if (!StringUtils.hasText(userId)) {
                log.warn("Token 中未找到用户ID: {}", path);
                return unauthorizedResponse(exchange, "认证令牌无效");
            }

            // 6. 验证 Token 有效性
            if (!tokenParser.validateToken(token, userId)) {
                log.warn("Token 验证失败: userId={}, path={}", userId, path);
                return unauthorizedResponse(exchange, "认证令牌验证失败");
            }

            // 7. 将用户信息添加到请求头中，传递给下游服务
            ServerHttpRequest mutatedRequest = request.mutate()
                    .header(AuthContants.USER_ID_ATTRIBUTE, userId)
                    .header(AuthContants.TOKEN_ATTRIBUTE, token)
                    .build();

            log.debug("Token 验证成功: userId={}, path={}", userId, path);

            // 8. 继续执行过滤器链
            return chain.filter(exchange.mutate().request(mutatedRequest).build());

        } catch (Exception e) {
            log.error("Token 解析或验证异常: path={}, error={}", path, e.getMessage(), e);
            return unauthorizedResponse(exchange, "认证令牌解析失败: " + e.getMessage());
        }
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isWhitelisted(String path) {
        // 1. 检查认证相关接口
        if (authProperties.getAuthPaths() != null) {
            for (String pattern : authProperties.getAuthPaths()) {
                if (pattern != null && pathMatcher.match(pattern, path)) {
                    return true;
                }
            }
        }

        // 2. 检查通用白名单
        if (authProperties.getWhitelist() != null) {
            for (String pattern : authProperties.getWhitelist()) {
                if (pattern != null && pathMatcher.match(pattern, path)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 从请求头或URL参数中提取 Token
     */
    private String extractToken(ServerHttpRequest request) {
        // 1. 优先从请求头获取
        List<String> headers = request.getHeaders().get(authProperties.getTokenHeader());
        if (headers != null && !headers.isEmpty()) {
            String header = headers.get(0);
            if (StringUtils.hasText(header)) {
                // 支持 Bearer 前缀
                String prefix = authProperties.getTokenPrefix();
                if (StringUtils.hasText(prefix) && header.startsWith(prefix)) {
                    return header.substring(prefix.length()).trim();
                }
                // 也支持直接传递 Token（不带前缀）
                return header.trim();
            }
        }

        // 2. 从URL参数获取（用于WebSocket连接）
        String tokenParam = request.getQueryParams().getFirst("token");
        if (StringUtils.hasText(tokenParam)) {
            log.debug("从URL参数获取Token");
            return tokenParam.trim();
        }

        return null;
    }

    /**
     * 返回未授权响应
     */
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        ResultDomain<Object> result = ResultDomain.failure(HttpStatus.UNAUTHORIZED.value(), message);
        String json = JSON.toJSONString(result);
        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        // 优先级设置为最高，确保在其他过滤器之前执行
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
