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

namespace QRRapidoApp.Services
{
    public class AdDisplayService
    {
        private readonly IUserService _userService;
        private readonly MongoDbContext _context;
        private readonly IConfiguration _config;
        private readonly ILogger<AdDisplayService> _logger;

        public AdDisplayService(IUserService userService, MongoDbContext context, IConfiguration config, ILogger<AdDisplayService> logger)
        {
            _userService = userService;
            _context = context;
            _config = config;
            _logger = logger;
        }

        public async Task<bool> ShouldShowAds(string? userId = null)
        {
            try
            {
                if (string.IsNullOrEmpty(userId))
                    return true;

                var user = await _userService.GetUserAsync(userId);
                if (user == null) return true;

                // Nova Lógica: Se tem créditos OU ainda tem cota grátis, não mostra anúncios
                return !(user.Credits > 0 || user.FreeQRsUsed < 5);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error checking ad display status for user {userId}: {ex.Message}");
                return true; // Default to showing ads on error
            }
        }

        public async Task<bool> HasValidPremiumSubscription(string userId)
        {
            try
            {
                var user = await _userService.GetUserAsync(userId);
                // Nova Lógica: "Premium" visualmente agora significa ter saldo ou cota
                return user != null && (user.Credits > 0 || user.FreeQRsUsed < 5);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error checking premium subscription for user {userId}: {ex.Message}");
                return false;
            }
        }

        public async Task<string> GetAdFreeStatusAsync(string userId)
        {
            try
            {
                if (await HasValidPremiumSubscription(userId))
                    return "Premium";

                return "None";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error getting ad-free status for user {userId}: {ex.Message}");
                return "None";
            }
        }

        public async Task<DateTime?> GetAdFreeExpiryDate(string userId)
        {
            try
            {
                var user = await _userService.GetUserAsync(userId);
                if (user?.IsPremium == true && user.PremiumExpiresAt > DateTime.UtcNow)
                    return user.PremiumExpiresAt;

                return null; // Sem sessões ad-free temporárias
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error getting ad-free expiry date for user {userId}: {ex.Message}");
                return null;
            }
        }

        public async Task DeactivateExpiredSessionsAsync()
        {
            try
            {
                var filter = Builders<AdFreeSession>.Filter.And(
                    Builders<AdFreeSession>.Filter.Eq(s => s.IsActive, true),
                    Builders<AdFreeSession>.Filter.Lt(s => s.ExpiresAt, DateTime.UtcNow)
                );

                var update = Builders<AdFreeSession>.Update.Set(s => s.IsActive, false);
                
                var result = await _context.AdFreeSessions.UpdateManyAsync(filter, update);
                
                if (result.ModifiedCount > 0)
                {
                    _logger.LogInformation($"Deactivated {result.ModifiedCount} expired ad-free sessions");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error deactivating expired sessions: {ex.Message}");
            }
        }

        public void SetViewBagAds(dynamic viewBag)
        {
            viewBag.AdSenseTag = _config["AdSense:ClientId"];
            viewBag.AdSenseEnabled = bool.TryParse(_config["AdSense:Enabled"], out var enabled) && enabled;
        }
    }
}
