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

namespace Managing.Application.Agents;

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

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

    public async Task<AgentBalanceHistory> GetAgentBalances(string agentName, DateTime start,
        DateTime? end = null)
    {
        // Get userId from agentName by looking up the user
        var userId = await ServiceScopeHelpers.WithScopedService<IUserService, int?>(_serviceScopeFactory,
            async (userService) =>
            {
                var user = await userService.GetUserByAgentName(agentName);
                return user?.Id;
            });

        if (!userId.HasValue)
        {
            // Return empty result if user not found
            return new AgentBalanceHistory
            {
                UserId = 0,
                AgentName = agentName,
                AgentBalances = new List<AgentBalance>()
            };
        }

        // Use the UserId-based method internally
        var result = await GetAgentBalancesByUserId(userId.Value, start, end);
        
        // Override the AgentName to use the requested agentName instead of the default
        result.AgentName = agentName;

        return result;
    }

    public async Task<AgentBalanceHistory> GetAgentBalancesByUserId(int userId, DateTime start,
        DateTime? end = null)
    {
        var effectiveEnd = end ?? DateTime.UtcNow;
        string cacheKey = $"AgentBalancesByUserId_{userId}_{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.GetAgentBalancesByUserId(userId, start, end);

        // Create a single AgentBalanceHistory with all balances
        var result = new AgentBalanceHistory
        {
            UserId = userId,
            AgentName = $"User_{userId}",
            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 SaveOrUpdateAgentSummary(AgentSummary agentSummary)
    {
        try
        {
            if (string.IsNullOrEmpty(agentSummary.AgentName))
            {
                agentSummary.AgentName = await ServiceScopeHelpers.WithScopedService<IUserService, string>(_serviceScopeFactory, 
                    async (userService) => (await userService.GetUserByIdAsync(agentSummary.UserId)).AgentName);
            }
            // 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);
    }

    public async Task UpdateAgentSummaryNameAsync(int userId, string agentName)
    {
        try
        {
            await _agentSummaryRepository.UpdateAgentNameAsync(userId, agentName);
            
            _logger.LogInformation("Agent name updated for user {UserId} to {AgentName}", userId, agentName);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error updating agent name for user {UserId} to {AgentName}", userId, agentName);
            throw;
        }
    }

    public async Task<int> GetTotalAgentCount()
    {
        return await _agentSummaryRepository.GetTotalAgentCount();
    }

    public async Task IncrementBacktestCountAsync(int userId)
    {
        try
        {
            await _agentSummaryRepository.IncrementBacktestCountAsync(userId);
            
            _logger.LogInformation("Backtest count incremented for user {UserId}", userId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error incrementing backtest count for user {UserId}", userId);
            throw;
        }
    }
}