package com.zhentao.config;

import io.minio.MinioClient;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        System.out.println("========== 初始化MinIO客户端（优化版） ==========");
        System.out.println("Endpoint: " + endpoint);
        System.out.println("AccessKey: " + accessKey);
        
        try {
            // 创建自定义的OkHttpClient，设置更长的超时时间
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.MINUTES)      // 连接超时：5分钟
                    .writeTimeout(5, TimeUnit.MINUTES)        // 写入超时：5分钟
                    .readTimeout(5, TimeUnit.MINUTES)         // 读取超时：5分钟
                    .callTimeout(10, TimeUnit.MINUTES)        // 总超时：10分钟
                    .retryOnConnectionFailure(true)           // 连接失败时自动重试
                    .build();
            
            MinioClient client = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .httpClient(httpClient)  // 使用自定义的HttpClient
                    .build();
            
            System.out.println("✓ MinIO客户端初始化成功（已优化超时配置）");
            System.out.println("  - 连接超时: 5分钟");
            System.out.println("  - 写入超时: 5分钟");
            System.out.println("  - 读取超时: 5分钟");
            System.out.println("  - 自动重试: 已启用");
            
            return client;
        } catch (Exception e) {
            System.err.println("✗ MinIO客户端初始化失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}


