package com.vetti.common.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 java.net.http.HttpClient;
import java.time.Duration;
import java.util.concurrent.Executors;

/**
 * @author ID
 * @date 2025/9/1 16:21
 */
@Configuration
public class HttpClientConfig {

    @Value("${http.client.connect-timeout-seconds:10}")
    private Integer connectTimeoutSeconds;


    /**
     * 创建并配置 HttpClient Bean.
     * 该实例线程安全，建议在整个应用中复用。
     *
     * @return 配置好的 HttpClient 实例
     */
    @Bean
    public HttpClient httpClient() {
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)              // 优先使用 HTTP/2，若服务器不支持则降级至 HTTP/1.1
                .connectTimeout(Duration.ofSeconds(connectTimeoutSeconds))          // 建立连接的超时时间
                .followRedirects(HttpClient.Redirect.NORMAL)     // 处理重定向策略 (NORMAL: 同协议重定向)
                .executor(Executors.newVirtualThreadPerTaskExecutor()) // 使用虚拟线程执行器（Java 21+，可选）
                .build();
    }
}
