package com.storycove.config;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(
    value = "storycove.search.engine",
    havingValue = "solr",
    matchIfMissing = false
)
public class SolrConfig {

    private static final Logger logger = LoggerFactory.getLogger(SolrConfig.class);

    private final SolrProperties properties;

    public SolrConfig(SolrProperties properties) {
        this.properties = properties;
    }

    @Bean
    public SolrClient solrClient() {
        logger.info("Initializing Solr client with URL: {}", properties.getUrl());

        HttpSolrClient.Builder builder = new HttpSolrClient.Builder(properties.getUrl())
            .withConnectionTimeout(properties.getConnection().getTimeout())
            .withSocketTimeout(properties.getConnection().getSocketTimeout());

        SolrClient client = builder.build();

        logger.info("Solr running without authentication");

        // Test connection
        testConnection(client);

        return client;
    }

    private void testConnection(SolrClient client) {
        try {
            // Test connection by pinging the server
            var response = client.ping();
            logger.info("Solr connection successful - Response time: {}ms",
                response.getElapsedTime());
        } catch (Exception e) {
            logger.warn("Solr connection test failed during initialization: {}", e.getMessage());
            logger.debug("Solr connection test full error", e);
            // Don't throw exception here - let the client be created and handle failures in service methods
        }
    }
}