using Aberwyn.Data;

namespace Aberwyn.Services
{
    public class TorrentRssService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<TorrentRssService> _logger;

        public TorrentRssService(IServiceProvider serviceProvider, ILogger<TorrentRssService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // Vänta lite innan första körningen
            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using var scope = _serviceProvider.CreateScope();
                    var rssProcessor = scope.ServiceProvider.GetRequiredService<IRssProcessor>();
                    await rssProcessor.ProcessRssFeeds();

                    _logger.LogInformation("RSS feeds processed successfully at {Time}", DateTime.UtcNow);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error processing RSS feeds");
                }

                // Vänta 10 minuter innan nästa körning
                await Task.Delay(TimeSpan.FromMinutes(10), stoppingToken);
            }
        }
    }
}