package com.arms.config;

import org.opensearch.action.admin.cluster.health.ClusterHealthRequest;
import org.opensearch.action.admin.cluster.health.ClusterHealthResponse;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomElasticsearchHealthIndicator implements HealthIndicator {

    private final RestHighLevelClient elasticsearchClient;

    public CustomElasticsearchHealthIndicator(RestHighLevelClient elasticsearchClient) {
        this.elasticsearchClient = elasticsearchClient;
    }

    @Override
    public Health health() {
        try {
            ClusterHealthResponse response = elasticsearchClient.cluster()
                    .health(new ClusterHealthRequest(), RequestOptions.DEFAULT);

            return Health.up()
                    .withDetail("cluster_name", response.getClusterName())
                    .withDetail("status", response.getStatus())
                    .withDetail("number_of_nodes", response.getNumberOfNodes())
                    .build();

        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}
