using Health.Application.Notifications;

namespace Health.WebApi.BackgroundServices;

public sealed class NotificationOutboxWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<NotificationOutboxWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var nextRecovery = DateTime.MinValue;
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = scopeFactory.CreateScope();
                var processor = scope.ServiceProvider.GetRequiredService<INotificationOutboxProcessor>();
                if (DateTime.UtcNow >= nextRecovery)
                {
                    await processor.RecoverStaleAsync(stoppingToken);
                    nextRecovery = DateTime.UtcNow.AddMinutes(1);
                }
                if (!await processor.ProcessNextAsync(stoppingToken))
                    await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "通知 Outbox 消费失败");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }
    }
}
