package com.multictrl.common.config;

import com.influxdb.LogLevel;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.InfluxDBClientOptions;
import lombok.Data;
import okhttp3.ConnectionPool;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * influxdb配置
 *
 * @author Sdy
 * @since 1.0.0 2026/5/3
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "influx")
public class InfluxConfig {

    private Boolean saveOpen;
    private String url;
    private String token;
    private String org;
    private String bucket;

    @Bean
    public InfluxDBClient influxDBClient() {
        // 1. 构建高性能 OkHttpClient（连接池+重试）
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder()
                .connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT))
                .connectTimeout(Duration.ofSeconds(15))
                .readTimeout(Duration.ofSeconds(300))
                .writeTimeout(Duration.ofSeconds(120))
                .connectionPool(new ConnectionPool(
                        20,
                        300,
                        TimeUnit.SECONDS
                ))
                .retryOnConnectionFailure(true)
                .addInterceptor(new HttpLoggingInterceptor(message ->
                        LoggerFactory.getLogger("InfluxDB").debug("HTTP: {}", message)
                ).setLevel(HttpLoggingInterceptor.Level.NONE));

        // 2. 通过 Options 精确配置
        InfluxDBClientOptions options = InfluxDBClientOptions.builder()
                .url(url)
                .authenticateToken(token.toCharArray())
                .org(org)
                .bucket(bucket)
                .okHttpClient(okHttpClient)
                .build();

        InfluxDBClient client = InfluxDBClientFactory.create(options);
        client.setLogLevel(LogLevel.NONE);
        return client;
    }
}
