package com.erp.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Configuration
public class RateLimitConfig {

    /**
     * 基于IP的限流
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            ServerHttpRequest request = exchange.getRequest();
            String ip = request.getRemoteAddress() != null
                    ? request.getRemoteAddress().getAddress().getHostAddress()
                    : "unknown";
            return Mono.just(ip);
        };
    }

    /**
     * 基于用户名的限流
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> {
            String username = exchange.getRequest().getHeaders().getFirst("X-User-Name");
            return Mono.just(username != null ? username : "anonymous");
        };
    }

    /**
     * 基于路径的限流
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest().getURI().getPath()
        );
    }

    /**
     * 基于路径+用户的复合限流
     */
    @Bean
    public KeyResolver compositeKeyResolver() {
        return exchange -> {
            String userName = exchange.getRequest().getHeaders().getFirst("X-User-Name");
            String path = exchange.getRequest().getURI().getPath();
            String clientIp = exchange.getRequest().getRemoteAddress() != null
                    ? exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
                    : "unknown";

            String compositeKey = String.format("%s:%s:%s", clientIp, userName, path);
            return Mono.just(compositeKey);
        };
    }
}
