package cn.novalon.manage.gateway.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 连接池配置
 * 
 * 文件定义：配置HTTP连接池参数
 * 涉及业务：连接池管理、超时控制、性能优化
 * 
 * 配置内容：
 * 1. 连接池大小
 * 2. 连接超时
 * 3. 读写超时
 * 4. 连接空闲时间
 * 
 * @author 张翔
 * @date 2026-03-26
 */
@Configuration
public class ConnectionPoolConfig {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolConfig.class);

    @Bean
    public HttpClient httpClient() {
        ConnectionProvider connectionProvider = ConnectionProvider.builder("gateway-pool")
                .maxConnections(500)
                .maxIdleTime(Duration.ofSeconds(20))
                .maxLifeTime(Duration.ofSeconds(60))
                .pendingAcquireTimeout(Duration.ofSeconds(45))
                .pendingAcquireMaxCount(1000)
                .evictInBackground(Duration.ofSeconds(120))
                .build();

        HttpClient httpClient = HttpClient.create(connectionProvider)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .doOnConnected(conn -> {
                    conn.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS));
                    conn.addHandlerLast(new WriteTimeoutHandler(10, TimeUnit.SECONDS));
                })
                .responseTimeout(Duration.ofSeconds(10));

        logger.info("HTTP client configured with connection pool");
        logger.info("Max connections: 500");
        logger.info("Connect timeout: 5000ms");
        logger.info("Read/Write timeout: 10s");

        return httpClient;
    }

    @Bean
    public ReactorClientHttpConnector reactorClientHttpConnector(HttpClient httpClient) {
        return new ReactorClientHttpConnector(httpClient);
    }
}
