using back.healthchecks.Options; using back.Options; using MCVIngenieros.Healthchecks; using MCVIngenieros.Healthchecks.Abstracts; using Microsoft.Extensions.Options; namespace back.healthchecks; public class SqliteHealthCheck(IOptionsMonitor databaseConfig, IOptionsMonitor healthchecksConfig) : HealthCheck { private readonly DatabaseConfig databaseConfig = databaseConfig.Get(DatabaseConfig.DataStorage); private readonly HealthChecksConfigs hcConfig = healthchecksConfig.Get(HealthChecksConfigs.Sqlite); public string Description => "Conecta con la base de datos SQLite y trata de hacer una consulta sobre la tabla Users."; public int? RetryAttempts => hcConfig.RetryAttempts ?? 2; public TimeSpan? Timeout => hcConfig.Timeout ?? TimeSpan.FromSeconds(5); public TimeSpan? RetryDelay => hcConfig.RetryDelay ?? TimeSpan.FromSeconds(1); public HealthCheckSeverity? Severity => hcConfig.Severity ?? HealthCheckSeverity.Critical; public override Task CheckAsync(CancellationToken cancellationToken = default) { var isHealthy = false; var details = string.Empty; try { using var connection = new Microsoft.Data.Sqlite.SqliteConnection(databaseConfig.ConnectionString); connection.Open(); using var command = connection.CreateCommand(); command.CommandText = $"SELECT COUNT(1) FROM Users WHERE Id = '{DataModels.User.SystemUserId}';"; var result = command.ExecuteScalar(); if (result != null && Convert.ToInt32(result) == 1) { isHealthy = true; details = "Connection to SQLite database successful and SystemUser exists."; } else { details = "Connection to SQLite database successful but SystemUser does not exist."; } } catch (Exception ex) { details = $"Failed to connect to SQLite database: {ex.Message}"; } return Task.FromResult(new HealthCheckResult(isHealthy) { Details = details, Severity = isHealthy ? HealthCheckSeverity.Info : HealthCheckSeverity.Critical }); } }