namespace PlotLine.Services;

public sealed class PersistedStoryIntelligenceWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<PersistedStoryIntelligenceWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(3));
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = scopeFactory.CreateScope();
                var runner = scope.ServiceProvider.GetRequiredService<IPersistedStoryIntelligenceRunner>();
                await runner.ProcessNextAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                return;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Persisted Story Intelligence worker failed while processing the next queued run.");
            }

            await timer.WaitForNextTickAsync(stoppingToken);
        }
    }
}
