package com.storlead.es.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch 客户端，仅在 {@code storlead.es.enabled=true} 时创建。
 */
@Configuration
@ConditionalOnProperty(prefix = "storlead.es", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(EsProperties.class)
public class ElasticSearchConfig {

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient(EsProperties properties) {
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (properties.getUsername() != null && !properties.getUsername().isEmpty()) {
            credentialsProvider.setCredentials(
                    AuthScope.ANY,
                    new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));
        }
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(properties.getHost(), properties.getPort(), properties.getScheme()))
                        .setHttpClientConfigCallback(httpClientBuilder ->
                                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
    }
}
