package com.tzld.piaoquan.ad.engine.server.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestClientConfig {

    @Value("${rest.eureka.connect-timeout-ms:2000}")
    private int connectTimeoutMs;

    @Value("${rest.eureka.read-timeout-ms:5000}")
    private int readTimeoutMs;

    @Value("${rest.eureka.connection-request-timeout-ms:2000}")
    private int connectionRequestTimeoutMs;

    @Value("${rest.eureka.pool.max-total:100}")
    private int maxTotal;

    @Value("${rest.eureka.pool.max-per-route:20}")
    private int maxPerRoute;

    @Bean(name = "eurekaRestTemplate")
    public RestTemplate eurekaRestTemplate() {
        // Connection pool
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);
        cm.setDefaultMaxPerRoute(maxPerRoute);

        // Timeouts
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeoutMs)
                .setSocketTimeout(readTimeoutMs)
                .setConnectionRequestTimeout(connectionRequestTimeoutMs)
                .build();

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(requestConfig)
                .evictIdleConnections(30, java.util.concurrent.TimeUnit.SECONDS)
                .build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        // Also set timeouts at factory level (some Spring versions prefer this)
        factory.setConnectTimeout(connectTimeoutMs);
        factory.setReadTimeout(readTimeoutMs);
        factory.setConnectionRequestTimeout(connectionRequestTimeoutMs);

        return new RestTemplate(factory);
    }
}

