using Cassandra;
using JiShe.CollectBus.Cassandra;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace JiShe.CollectBus.Host.HealthChecks
{
    /// <summary>
    /// CassandraHealthCheck
    /// </summary>
    /// <seealso cref="Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck" />
    public class CassandraHealthCheck : IHealthCheck
    {
        private readonly IConfiguration _configuration;

        /// <summary>
        /// Initializes a new instance of the <see cref="CassandraHealthCheck"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public CassandraHealthCheck(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// Runs the health check, returning the status of the component being checked.
        /// </summary>
        /// <param name="context">A context object associated with the current execution.</param>
        /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> that can be used to cancel the health check.</param>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task`1" /> that completes when the health check has finished, yielding the status of the component being checked.
        /// </returns>
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            var cassandraConfig = new CassandraConfig();
            _configuration.GetSection("Cassandra").Bind(cassandraConfig);
            try
            {
                var clusterBuilder = Cluster.Builder();
                foreach (var node in cassandraConfig.Nodes)
                {
                    clusterBuilder.AddContactPoint(node.Host)
                        .WithPort(node.Port);
                }
                clusterBuilder.WithCredentials(cassandraConfig.Username, cassandraConfig.Password);
                var cluster = clusterBuilder.Build();
                using var session = await cluster.ConnectAsync();
                var result = await Task.FromResult(session.Execute("SELECT release_version FROM system.local"));
                var version = result.First().GetValue<string>("release_version");
                return HealthCheckResult.Healthy($"Cassandra is healthy. Version: {version}");
            }
            catch (Exception ex)
            {
                return new HealthCheckResult(context.Registration.FailureStatus, $"Cassandra is unhealthy: {ex.Message}", ex);
            }
        }
    }
} 