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.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

/**
 * ES 域自动配置：始终注册 {@link com.storlead.es.service.EsSearchCustomerService}（Noop 或真实实现）。
 */
@Configuration
@EnableConfigurationProperties(EsProperties.class)
@ComponentScan(basePackages = {
        "com.storlead.es.service.impl",
        "com.storlead.es.server.impl"
})
public class EsAutoConfiguration {

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

        @Bean(destroyMethod = "close")
        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)));
        }

        @Bean
        ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient restHighLevelClient) {
            return new ElasticsearchRestTemplate(restHighLevelClient);
        }
    }
}
