package org.xyzh.gateway.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Gateway诊断控制器 - 用于检查路由配置
 * 
 * @author yslg
 * @since 2025-12-11
 */
@RestController
@RequestMapping("/gateway-diagnostic")
public class GatewayDiagnosticController {

    @Autowired
    private RouteLocator routeLocator;

    /**
     * 获取所有路由信息
     * 访问: http://localhost:8180/gateway-diagnostic/routes
     */
    @GetMapping("/routes")
    public Flux<Map<String, Object>> getRoutes() {
        return routeLocator.getRoutes()
            .map(route -> {
                Map<String, Object> routeInfo = new HashMap<>();
                routeInfo.put("id", route.getId());
                routeInfo.put("uri", route.getUri().toString());
                routeInfo.put("order", route.getOrder());
                routeInfo.put("predicates", route.getPredicate().toString());
                routeInfo.put("filters", route.getFilters().toString());
                return routeInfo;
            });
    }

    /**
     * 健康检查
     * 访问: http://localhost:8180/gateway-diagnostic/health
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("message", "Gateway is running");
        health.put("timestamp", System.currentTimeMillis());
        return health;
    }
}
