using Microsoft.Data.Sqlite;

namespace Watcher.Services;

public class DatabaseCheck : BackgroundService
{
    private readonly ILogger<DatabaseCheck> _logger;

    private IDashboardStore _dashboardStore;

    public DatabaseCheck(ILogger<DatabaseCheck> logger, IDashboardStore dashboardStore)
    {
        _logger = logger;
        _dashboardStore = dashboardStore;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));

        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            // Hintergrundprozess abwarten
            await CheckDatabaseIntegrity();
            // 5 Sekdunden Offset
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
    }

    // String sqliteConnectionString als Argument übergeben
    public Task CheckDatabaseIntegrity()
    {
        using var conn = new SqliteConnection("Data Source=./persistence/watcher.db");
        _logger.LogInformation("Sqlite Integrity-Check started...");

        try
        {
            conn.Open();

            using var command = conn.CreateCommand();
            command.CommandText = """
                SELECT integrity_check FROM pragma_integrity_check;
                """;

            using var reader = command.ExecuteReader();

            while (reader.Read())
            {
                string status = reader.GetString(0);
                _dashboardStore.DatabaseStatus = status;
                _logger.LogInformation("Sqlite DatabaseIntegrity: ${status}", status);
            }

            conn.Close();
        }
        catch (SqliteException e)
        {
            conn.Close();
            _logger.LogError(e.Message);

            // TODO: LogEvent erstellen
        }

        _logger.LogInformation("Database Integrity-Check finished.");
        return Task.CompletedTask;
    }
}