using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace PromotionService.API.HealthChecks;

/// <summary>
/// EN: Health check for Wallet Service connectivity.
/// VI: Kiểm tra sức khỏe kết nối Wallet Service.
/// </summary>
public class WalletServiceHealthCheck : IHealthCheck
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<WalletServiceHealthCheck> _logger;

    public WalletServiceHealthCheck(IHttpClientFactory httpClientFactory, ILogger<WalletServiceHealthCheck> logger)
    {
        _httpClient = httpClientFactory.CreateClient("WalletService");
        _logger = logger;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync("/health/live", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                return HealthCheckResult.Healthy("Wallet Service is reachable");
            }

            _logger.LogWarning("Wallet Service health check failed with status {StatusCode}", response.StatusCode);
            return HealthCheckResult.Degraded($"Wallet Service returned {response.StatusCode}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Wallet Service health check failed");
            return HealthCheckResult.Unhealthy("Wallet Service is not reachable", ex);
        }
    }
}
