package cn.reghao.tnb.gateway.limiter;

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

import java.util.Objects;

/**
 * @author reghao
 * @date 2025-07-17 10:24:14
 */
@Slf4j
@Configuration
public class MyKeyResolverConfig {
    /**
     * 根据请求 IP 限流
     *
     * @param
     * @return
     * @date 2025-07-16 09:55:42
     */
    @Bean("keyResolver")
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(Objects.requireNonNull(
                exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress()));
    }

    /**
     * 根据请求路径限流
     *
     * @param
     * @return
     * @date 2025-07-16 09:56:45
     */
    //@Bean("keyResolver")
    public KeyResolver pathKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                ServerHttpRequest request = exchange.getRequest();
                String path = request.getURI().getPath();
                String remoteAddr = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
                log.info("{} -> {}", path, remoteAddr);
                return Mono.just(path);
            }
        };
    }

    /**
     * 根据请求参数限流(这里根据 userId 参数)
     *
     * @param
     * @return
     * @date 2025-07-16 09:55:59
     */
    //@Bean(name = "keyResolver")
    public KeyResolver userKeyResolver() {
        String paramName = "userId";
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest()
                .getQueryParams()
                .getFirst(paramName))
        );
    }
}
