using Dapper;
using Npgsql;

namespace Kbx.Shared.Runtime;

public sealed class KbxRuntimeNoticeRepository(NpgsqlDataSource dataSource)
{
    public async Task<KbxRuntimeNotice?> GetActiveAsync(Guid tenantId, CancellationToken ct)
    {
        const string sql = """
        select mode as Mode, title, message, started_at as Since,
               correlation_id as CorrelationId
          from kbx.runtime_incidents
         where ended_at is null
           and (tenant_id is null or tenant_id=@tenantId)
         order by case mode when 'read-only' then 0 when 'offline' then 1 else 2 end,
                  started_at desc
         limit 1;
        """;
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        var row = await connection.QuerySingleOrDefaultAsync<RuntimeNoticeRow>(new CommandDefinition(sql, new { tenantId }, cancellationToken: ct));
        if (row is null) return null;
        var mode = row.Mode switch {
            "read-only" => KbxRuntimeMode.ReadOnly,
            "offline" => KbxRuntimeMode.Offline,
            _ => KbxRuntimeMode.Degraded,
        };
        return new KbxRuntimeNotice(mode, row.Title, row.Message, row.Since, row.CorrelationId, mode is KbxRuntimeMode.Degraded or KbxRuntimeMode.Offline);
    }

    private sealed record RuntimeNoticeRow(string Mode, string Title, string? Message, DateTimeOffset Since, string? CorrelationId);
}
