package com.seer.teach.filter.route;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class DiagnosticFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 2; // 最高优先级
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=== GATEWAY DIAGNOSTICS START ===");

        // 1. 打印请求信息
        log.info("Request: " + exchange.getRequest().getMethod() + " " +
                exchange.getRequest().getURI());

        // 2. 检查路由是否匹配
        Object routeAttr = exchange.getAttribute("org.springframework.cloud.gateway.support.ServerWebExchangeUtils.gatewayRoute");
        log.info("Route matched: " + (routeAttr != null));

        // 3. 检查负载均衡属性
        Object lbUriAttr = exchange.getAttribute("org.springframework.cloud.gateway.support.ServerWebExchangeUtils.gatewayLoadBalancerRequestUri");
        log.info("LoadBalancer URI: " + lbUriAttr);

        // 4. 检查服务发现状态
        log.info("Service instances: " +
                (exchange.getAttribute("org.springframework.cloud.client.discovery.DiscoveryClient") != null));

        log.info("=== GATEWAY DIAGNOSTICS END ===");

        return chain.filter(exchange);
    }
}
