using QRRapidoApp.Data;
using QRRapidoApp.Models;
using MongoDB.Driver;

namespace QRRapidoApp.Services
{
    public class HistoryCleanupService : BackgroundService
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly ILogger<HistoryCleanupService> _logger;
        private readonly IConfiguration _configuration;

        public HistoryCleanupService(IServiceScopeFactory scopeFactory, ILogger<HistoryCleanupService> logger, IConfiguration configuration)
        {
            _scopeFactory = scopeFactory;
            _logger = logger;
            _configuration = configuration;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var gracePeriodDays = _configuration.GetValue<int>("HistoryCleanup:GracePeriodDays", 7);
            var cleanupIntervalHours = _configuration.GetValue<int>("HistoryCleanup:CleanupIntervalHours", 6);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using var scope = _scopeFactory.CreateScope();
                    var context = scope.ServiceProvider.GetRequiredService<MongoDbContext>();
                    
                    if (context.IsConnected && context.Users != null && context.QRCodeHistory != null)
                    {
                        // Buscar usuários que cancelaram há mais de X dias
                        var cutoffDate = DateTime.UtcNow.AddDays(-gracePeriodDays);
                        
                        var usersToCleanup = await context.Users
                            .Find(u => u.PremiumCancelledAt != null && 
                                      u.PremiumCancelledAt < cutoffDate &&
                                      u.QRHistoryIds.Count > 0)
                            .ToListAsync(stoppingToken);
                        
                        foreach (var user in usersToCleanup)
                        {
                            // Remover histórico de QR codes
                            if (user.QRHistoryIds.Any())
                            {
                                await context.QRCodeHistory.DeleteManyAsync(
                                    qr => user.QRHistoryIds.Contains(qr.Id), stoppingToken);
                                
                                // Limpar lista de histórico do usuário
                                var update = Builders<User>.Update.Set(u => u.QRHistoryIds, new List<string>());
                                await context.Users.UpdateOneAsync(u => u.Id == user.Id, update, cancellationToken: stoppingToken);
                                
                                _logger.LogInformation($"Histórico removido para usuário {user.Id} - inadimplente há {gracePeriodDays}+ dias");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Erro no cleanup do histórico");
                }
                
                // Executar a cada X horas
                await Task.Delay(TimeSpan.FromHours(cleanupIntervalHours), stoppingToken);
            }
        }
    }
}