using System.Net.Sockets;
using JiShe.CollectBus.Cassandra;
using JiShe.CollectBus.IoTDB.Interface;
using JiShe.CollectBus.IoTDB.Options;
using JiShe.CollectBus.IoTDB.Provider;
using Microsoft.Extensions.Diagnostics.HealthChecks;

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

        /// <summary>
        /// Initializes a new instance of the <see cref="IoTdbHealthCheck"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public IoTdbHealthCheck(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)
        {
            try
            {
                // todo 此处需要单独创建连接，并需要在连接打开以后立即关闭，否则会影响整个连接的使用。
                //var ioTDbOptions = new IoTDbOptions();
                //_configuration.GetSection("IoTDBOptions").Bind(ioTDbOptions);
                //var pool = new SessionPoolAdapter(ioTDbOptions);
                //await pool.OpenAsync();
                return HealthCheckResult.Healthy($"IoTDB is healthy.");
            }
            catch (Exception ex)
            {
                return new HealthCheckResult(context.Registration.FailureStatus, $"IoTDB不健康: {ex.Message}", ex);
            }
        }
    }
} 