using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Predictalytics.Application.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Predictalytics.Worker.Services;

/// <summary>
/// Background service that periodically recalculates scores and ranks for all traders
/// and evaluates system alerts. Decoupled from the 60-second polling cycle.
/// </summary>
public class ScoringAndAlertsWorker : BackgroundService
{
    private readonly IServiceProvider _services;
    private readonly ILogger<ScoringAndAlertsWorker> _logger;
    private readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(15);

    public ScoringAndAlertsWorker(IServiceProvider services, ILogger<ScoringAndAlertsWorker> logger)
    {
        _services = services;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("📈 ScoringAndAlertsWorker started (recalculation interval: {Interval}m)", _checkInterval.TotalMinutes);
        await Task.Delay(10000, stoppingToken); // Let system initialize

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                _logger.LogInformation("📈 ScoringAndAlertsWorker: Starting recalculation cycle...");

                using (var scope = _services.CreateScope())
                {
                    var scoringService = scope.ServiceProvider.GetRequiredService<IScoringService>();
                    var alertService = scope.ServiceProvider.GetRequiredService<IAlertService>();

                    await scoringService.RecalculateAllScoresAsync(stoppingToken);
                    await alertService.EvaluateAlertsAsync(stoppingToken);
                }

                _logger.LogInformation("📈 ScoringAndAlertsWorker: Recalculation cycle complete.");
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                // App shutting down
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in ScoringAndAlertsWorker execution cycle");
            }

            await Task.Delay(_checkInterval, stoppingToken);
        }

        _logger.LogInformation("📈 ScoringAndAlertsWorker stopped");
    }
}
