using Microsoft.Extensions.Options;
using Pgo.Backend.Config;
using Pgo.Backend.Interfaces;

namespace Pgo.Backend.Services;

public class StelselnodeBackgroundService(IServiceProvider services, ILogger<StelselnodeBackgroundService> logger, IOptions<PgoConfig> pgoConfig) : BackgroundService
{
    private IServiceProvider Services { get; } = services;
    private readonly ILogger<StelselnodeBackgroundService> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    private readonly PgoConfig _pgoConfig = pgoConfig?.Value ?? throw new ArgumentNullException(nameof(pgoConfig));

    protected override async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        _logger.LogDebug("Stelselnode: background service running.");
        await DoWorkAsync(cancellationToken);
    }

    private async Task DoWorkAsync(CancellationToken cancellationToken)
    {
        using var scope = Services.CreateScope();
        await UpdateStelselnodeListsAsync(scope, cancellationToken);
    }

    private async Task UpdateStelselnodeListsAsync(IServiceScope scope, CancellationToken cancellationToken)
    {
        var stelselnodeService = scope.ServiceProvider.GetRequiredService<IStelselNodeService>();

        while (!cancellationToken.IsCancellationRequested)
        {
            _logger.LogInformation("Stelselnode: updating lists.");
            try
            {
                await stelselnodeService.UpdateStelselNodeListsAsync(cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError("Stelselnode: parsing of lists failed. Exception Message={Message}", ex.Message);
            }
            _logger.LogInformation("Stelselnode: updated lists. Waiting {minutes} minutes until next update.", _pgoConfig.UpdateStelselNodeIntervalMinutes);
            await Task.Delay(TimeSpan.FromMinutes(_pgoConfig.UpdateStelselNodeIntervalMinutes), cancellationToken);
        }
    }

    public override async Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogDebug("Stelselnode: bacjground service stopping.");
        await Task.CompletedTask;
    }
}

