package com.bb.config;

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

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

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        // 1. 커넥션 풀 설정 
        ConnectionProvider provider = ConnectionProvider.builder("my-connection-pool")
                .maxConnections(4096)               // 기존 MaxTotal(4096)과 매칭
                .pendingAcquireTimeout(Duration.ofMillis(3000))
                .maxIdleTime(Duration.ofSeconds(20))
                .build();

        // 2. 타임아웃 및 Netty HttpClient 설정
        HttpClient httpClient = HttpClient.create(provider)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) // 기존 ConnectTimeout(3000)과 매칭
                .responseTimeout(Duration.ofSeconds(8))            // 응답 대기 시간
                .doOnConnected(conn -> 
                    conn.addHandlerLast(new ReadTimeoutHandler(9, TimeUnit.SECONDS))
                        .addHandlerLast(new WriteTimeoutHandler(9, TimeUnit.SECONDS))
                );

        // 3. WebClient 빈 생성
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024)) // 2MB
                .build();
    }
}