using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using BCards.Web.Configuration; using Stripe; using System.Diagnostics; namespace BCards.Web.HealthChecks; public class StripeHealthCheck : IHealthCheck { private readonly StripeSettings _stripeSettings; private readonly ILogger _logger; public StripeHealthCheck(IOptions stripeSettings, ILogger logger) { _stripeSettings = stripeSettings.Value; _logger = logger; } public async Task CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default) { var stopwatch = Stopwatch.StartNew(); try { // Configura Stripe temporariamente para o teste StripeConfiguration.ApiKey = _stripeSettings.SecretKey; // Testa conectividade listando produtos (limite 1 para ser rápido) var productService = new ProductService(); var options = new ProductListOptions { Limit = 1 }; await productService.ListAsync(options, cancellationToken: cancellationToken); stopwatch.Stop(); var duration = stopwatch.ElapsedMilliseconds; _logger.LogInformation("Stripe health check completed successfully in {Duration}ms", duration); var data = new Dictionary { { "status", "healthy" }, { "duration", $"{duration}ms" }, { "api_key_prefix", _stripeSettings.SecretKey?.Substring(0, Math.Min(12, _stripeSettings.SecretKey.Length)) + "..." }, { "latency", duration } }; // Status baseado na latência if (duration > 10000) // > 10s return HealthCheckResult.Unhealthy($"Stripe response time too high: {duration}ms", data: data); if (duration > 5000) // > 5s return HealthCheckResult.Degraded($"Stripe response time elevated: {duration}ms", data: data); return HealthCheckResult.Healthy($"Stripe API is responsive ({duration}ms)", data: data); } catch (StripeException stripeEx) { stopwatch.Stop(); var duration = stopwatch.ElapsedMilliseconds; _logger.LogError(stripeEx, "Stripe health check failed after {Duration}ms: {Error}", duration, stripeEx.Message); var data = new Dictionary { { "status", "unhealthy" }, { "duration", $"{duration}ms" }, { "error", stripeEx.Message }, { "error_code", stripeEx.StripeError?.Code ?? "unknown" }, { "error_type", stripeEx.StripeError?.Type ?? "unknown" } }; return HealthCheckResult.Unhealthy($"Stripe API error: {stripeEx.Message}", stripeEx, data); } catch (Exception ex) { stopwatch.Stop(); var duration = stopwatch.ElapsedMilliseconds; _logger.LogError(ex, "Stripe health check failed after {Duration}ms", duration); var data = new Dictionary { { "status", "unhealthy" }, { "duration", $"{duration}ms" }, { "error", ex.Message } }; return HealthCheckResult.Unhealthy($"Stripe connection failed: {ex.Message}", ex, data); } } }