using Health.Application.Medications;

namespace Health.WebApi.BackgroundServices;

public sealed class MedicationReminderWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<MedicationReminderWorker> logger) : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
    private readonly ILogger<MedicationReminderWorker> _logger = logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("用药提醒持久化任务消费者已启动");
        var idleDelay = TimeSpan.FromSeconds(1);
        var nextRecovery = DateTime.MinValue;

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var queue = scope.ServiceProvider.GetRequiredService<IMedicationReminderQueue>();
                if (DateTime.UtcNow >= nextRecovery)
                {
                    await queue.RecoverStaleAsync(stoppingToken);
                    nextRecovery = DateTime.UtcNow.AddMinutes(1);
                }

                var task = await queue.TryTakeAsync(stoppingToken);
                if (task == null)
                {
                    await Task.Delay(idleDelay, stoppingToken);
                    idleDelay = TimeSpan.FromSeconds(Math.Min(idleDelay.TotalSeconds * 2, 5));
                    continue;
                }

                idleDelay = TimeSpan.FromSeconds(1);
                try
                {
                    var dispatcher = scope.ServiceProvider.GetRequiredService<IMedicationReminderDispatcher>();
                    await dispatcher.DispatchAsync(task, stoppingToken);
                    await queue.CompleteAsync(task.TaskId, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "用药提醒消费失败: {MedicationId}", task.MedicationId);
                    await queue.RetryAsync(task.TaskId, ex.Message, stoppingToken);
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用药提醒消费者循环异常");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }
    }
}
