package cn.reghao.tnb.gateway.limiter;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author reghao
 * @date 2025-07-16 10:02:14
 */
//@Configuration
public class LimiterConfig {
    private final MetricsRateLimiterFilter metricsRateLimiterFilter;

    public LimiterConfig(MetricsRateLimiterFilter metricsRateLimiterFilter) {
        this.metricsRateLimiterFilter = metricsRateLimiterFilter;
    }

    /**
     * 实现 RequestRateLimiterGatewayFilterFactory 和 RateLimiter 来限流
     *
     * @param
     * @return
     * @date 2025-07-17 15:33:36
     */
    //@Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("rate-limiter", r -> r.path("/api/content/**")
                        .filters(filter -> filter.requestRateLimiter()
                                .rateLimiter(MyRateLimiter.class, limiter -> limiter.setRequestedTokens(10))
                                .and()
                        )
                        .uri("lb://content-service")
                )
                .build();
    }

    /**
     * 实现 GatewayFilter 来限流
     *
     * @param
     * @return
     * @date 2025-07-17 15:32:51
     */
    //@Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/apit/content/**")
                        .filters(f -> f.stripPrefix(0).filter(metricsRateLimiterFilter))
                        .uri("lb://content-service")
                )
                .build();
    }

    /**
     * hystrix 熔断接口(需要 spring-cloud-starter-netflix-hystrix 依赖)
     *
     * @param
     * @return
     * @date 2025-07-17 14:38:13
     */
    //@Bean
    public RouterFunction<ServerResponse> fallbackRouter() {
        return RouterFunctions
                .route(RequestPredicates.GET("/fallback"), request -> ServerResponse
                        .status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.TEXT_PLAIN)
                        .body(Mono.just("timeout limiter"), String.class));
    }
}
