package org.hzhub.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * 限流配置
 * 基于 Redis 实现令牌桶限流
 */
@Configuration
public class RateLimiterConfig {

    /**
     * 注册 Redis 限流器 bean
     * replenishRate: 每秒补充的令牌数
     * burstCapacity: 令牌桶最大容量
     * requestedTokens: 每次请求消耗的令牌数
     */
    @Bean
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(10, 20, 1);
    }

    /**
     * 按 IP 地址限流（默认 KeyResolver）
     */
    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            String ip = exchange.getRequest().getRemoteAddress() != null
                ? exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
                : "unknown";
            return Mono.just("gateway:ratelimit:ip:" + ip);
        };
    }

    /**
     * 按路径 + IP 限流
     */
    @Bean
    public KeyResolver pathIpKeyResolver() {
        return exchange -> {
            String path = exchange.getRequest().getURI().getPath();
            String ip = exchange.getRequest().getRemoteAddress() != null
                ? exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
                : "unknown";
            return Mono.just("gateway:ratelimit:path:" + path + ":ip:" + ip);
        };
    }
}
