using Berufsschule_HAM.Services;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Berufsschule_HAM.HealthChecks;

public class DatabaseHealthCheck : IHealthCheck
{
    private readonly ILogger<DatabaseHealthCheck> _logger;
    private readonly LdapService _ldapService;

    public DatabaseHealthCheck(ILogger<DatabaseHealthCheck> logger, LdapService ldapService)
    {
        _logger = logger;
        _ldapService = ldapService;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        _logger.LogTrace("CheckHealthAsync - Checking health");
        try
        {
            await _ldapService.ListUsersAsync();
            await _ldapService.ListDeviceAsync();
            await _ldapService.ListGroupsAsync(["cn", "description"]);
            await _ldapService.ListLocationsAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "CheckHealthAsync - Unable to list users due to exception {ex.Message} - {ex.StackTrace}", [ex.Message, ex.StackTrace]);
            return HealthCheckResult.Unhealthy();
        }
        _logger.LogTrace("CheckHealthAsync - Health check successful");
        return HealthCheckResult.Healthy();
    }
}