using Confluent.Kafka;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;

public sealed class KafkaHealthCheck : IHealthCheck
{
    private readonly KafkaOptions _options;

    public KafkaHealthCheck(IOptions<KafkaOptions> options) => _options = options.Value;

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        using var admin = new AdminClientBuilder(new AdminClientConfig
        {
            BootstrapServers = _options.BootstrapServers
        }.ApplySecurity(_options)).Build();

        var metadata = await Task.Run(
            () => admin.GetMetadata(TimeSpan.FromSeconds(5)), cancellationToken);

        var data = new Dictionary<string, object> { ["brokers"] = metadata.Brokers.Count };
        return HealthCheckResult.Healthy(data: data);
    }
}
