using Microsoft.EntityFrameworkCore;

public sealed class OutboxPendingCollector : BackgroundService
{
    private readonly IServiceScopeFactory _scopes;
    private readonly ClinicalMetrics _metrics;
    private readonly ILogger<OutboxPendingCollector> _logger;

    public OutboxPendingCollector(
        IServiceScopeFactory scopes,
        ClinicalMetrics metrics,
        ILogger<OutboxPendingCollector> logger)
    {
        _scopes  = scopes;
        _metrics = metrics;
        _logger  = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
        while (await timer.WaitForNextTickAsync(ct))
            await CollectAsync(ct);
    }

    private async Task CollectAsync(CancellationToken ct)
    {
        try
        {
            await using var scope = _scopes.CreateAsyncScope();
            var db    = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            var count = await db.OutboxEvents
                .CountAsync(e => e.ProcessedAt == null, ct);

            _metrics.OutboxPendingEvents.Set(count);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "OutboxPendingCollector failed");
        }
    }
}