using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Statistics;
using Microsoft.Extensions.Logging;

namespace Managing.Application.Agents;

public class AgentService : IAgentService
{
    private readonly IAgentBalanceRepository _agentBalanceRepository;
    private readonly IAgentSummaryRepository _agentSummaryRepository;
    private readonly ICacheService _cacheService;
    private readonly ILogger<AgentService> _logger;

    public AgentService(
        IAgentBalanceRepository agentBalanceRepository,
        IAgentSummaryRepository agentSummaryRepository,
        ICacheService cacheService,
        ILogger<AgentService> logger)
    {
        _agentBalanceRepository = agentBalanceRepository;
        _agentSummaryRepository = agentSummaryRepository;
        _cacheService = cacheService;
        _logger = logger;
    }

    public async Task<AgentBalanceHistory> GetAgentBalances(string agentName, DateTime start,
        DateTime? end = null)
    {
        var effectiveEnd = end ?? DateTime.UtcNow;
        string cacheKey = $"AgentBalances_{agentName}_{start:yyyyMMdd}_{effectiveEnd:yyyyMMdd}";

        // Check if the balances are already cached
        var cachedBalances = _cacheService.GetValue<AgentBalanceHistory>(cacheKey);

        if (cachedBalances != null)
        {
            return cachedBalances;
        }

        var balances = await _agentBalanceRepository.GetAgentBalances(agentName, start, end);

        // Create a single AgentBalanceHistory with all balances
        var result = new AgentBalanceHistory
        {
            AgentName = agentName,
            AgentBalances = balances.OrderBy(b => b.Time).ToList()
        };

        // Cache the results for 5 minutes
        _cacheService.SaveValue(cacheKey, result, TimeSpan.FromMinutes(5));

        return result;
    }

    public async Task<(IList<AgentBalanceHistory> Agents, int TotalCount)> GetBestAgents(
        DateTime start,
        DateTime? end = null,
        int page = 1,
        int pageSize = 10)
    {
        var effectiveEnd = end ?? DateTime.UtcNow;
        string cacheKey = $"BestAgents_{start:yyyyMMdd}_{effectiveEnd:yyyyMMdd}";

        // Check if the results are already cached
        var cachedResult = _cacheService.GetValue<(IList<AgentBalanceHistory>, int)>(cacheKey);

        if (cachedResult != default)
        {
            // Apply pagination to cached results
            var (cachedAgents, cachedTotalCount) = cachedResult;
            var paginatedAgents = cachedAgents
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return (paginatedAgents, cachedTotalCount);
        }

        // Get all agents with their balance history
        var (fetchedAgents, fetchedTotalCount) =
            await _agentBalanceRepository.GetAllAgentBalancesWithHistory(start, end);

        // Cache all results for 5 minutes
        _cacheService.SaveValue(cacheKey, (fetchedAgents, fetchedTotalCount), TimeSpan.FromMinutes(5));

        // Apply pagination
        var result = fetchedAgents
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToList();

        return (result, fetchedTotalCount);
    }

    public async Task SaveOrUpdateAgentSummary(AgentSummary agentSummary)
    {
        try
        {
            // Use the injected AgentSummaryRepository to save or update
            await _agentSummaryRepository.SaveOrUpdateAsync(agentSummary);

            _logger.LogInformation("AgentSummary saved/updated for user {UserId} with agent name {AgentName}", 
                agentSummary.UserId, agentSummary.AgentName);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error saving/updating AgentSummary for user {UserId} with agent name {AgentName}", 
                agentSummary.UserId, agentSummary.AgentName);
            throw;
        }
    }

    public async Task<IEnumerable<AgentSummary>> GetAllAgentSummaries()
    {
        return await _agentSummaryRepository.GetAllAsync();
    }

    public async Task<IEnumerable<string>> GetAllOnlineAgents()
    {
        var agentSummaries = await _agentSummaryRepository.GetAllAgentWithRunningBots();
        return agentSummaries.Select(a => a.AgentName);
    }
}