using Microsoft.Extensions.Diagnostics.HealthChecks;
using MiningService.Infrastructure;

namespace MiningService.API.HealthChecks;

/// <summary>
/// EN: Health check for database connectivity.
/// VI: Health check cho kết nối database.
/// </summary>
public class DatabaseHealthCheck : IHealthCheck
{
    private readonly MiningServiceContext _context;

    public DatabaseHealthCheck(MiningServiceContext context)
    {
        _context = context;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default)
    {
        try
        {
            await _context.Database.CanConnectAsync(cancellationToken);
            return HealthCheckResult.Healthy("Database connection is healthy");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Database connection failed", ex);
        }
    }
}

/// <summary>
/// EN: Readiness check - service ready to accept traffic.
/// VI: Readiness check - dịch vụ sẵn sàng nhận traffic.
/// </summary>
public class ReadinessHealthCheck : IHealthCheck
{
    private readonly MiningServiceContext _context;

    public ReadinessHealthCheck(MiningServiceContext context)
    {
        _context = context;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default)
    {
        try
        {
            // Check database
            var canConnect = await _context.Database.CanConnectAsync(cancellationToken);
            if (!canConnect)
                return HealthCheckResult.Unhealthy("Cannot connect to database");

            return HealthCheckResult.Healthy("Service is ready");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Readiness check failed", ex);
        }
    }
}
