using Health.Application.Medications;

namespace Health.WebApi.BackgroundServices;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("用药提醒扫描生产者已启动");
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var scanner = scope.ServiceProvider.GetRequiredService<IMedicationReminderScanner>();
                var queue = scope.ServiceProvider.GetRequiredService<IMedicationReminderQueue>();
                var tasks = await scanner.ScanAsync(DateTime.UtcNow, stoppingToken);
                foreach (var task in tasks)
                    await queue.EnqueueAsync(task, stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用药提醒扫描异常");
            }

            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
        }
    }
}
