package com.tashow.cloud.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import javax.annotation.PreDestroy;

@Slf4j
@AutoConfiguration
public class ElasticsearchAutoConfiguration {

    private RestClient restClient;

    @Bean
    public ElasticsearchClient elasticsearchClient(ElasticsearchProperties properties) {
        // 1. 构建 HTTP 主机数组
        HttpHost[] hosts = properties.getUris().stream()
                .map(uri -> {
                    if (!uri.startsWith("http")) {
                        throw new IllegalArgumentException("URI 必须包含协议 (http/https)");
                    }
                    return HttpHost.create(uri);
                })
                .toArray(HttpHost[]::new);

        // 2. 创建低级 REST 客户端 (无认证)
        this.restClient = RestClient.builder(hosts)
                .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                        .setConnectTimeout(properties.getConnectTimeout())
                        .setSocketTimeout(properties.getSocketTimeout()))
                .build();

        // 3. 创建 Transport 层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient,
                new JacksonJsonpMapper() // 使用 Jackson 处理 JSON
        );

        log.info("[Elasticsearch] 客户端初始化完成，节点: {}", properties.getUris());
        return new ElasticsearchClient(transport);
    }

    @PreDestroy
    public void destroy() {
        if (restClient != null) {
            try {
                restClient.close();
                log.info("[Elasticsearch] 客户端已关闭");
            } catch (Exception e) {
                log.error("[Elasticsearch] 客户端关闭异常", e);
            }
        }
    }
}