using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.ManageBot.Commands;
using Managing.Domain.Bots;
using Managing.Domain.Users;
using MediatR;

namespace Managing.Application.ManageBot
{
    /// <summary>
    /// Handler for retrieving all agents and their strategies
    /// </summary>
    public class GetAllAgentsCommandHandler : IRequestHandler<GetAllAgentsCommand, Dictionary<User, List<Bot>>>
    {
        private readonly IBotService _botService;
        private readonly IUserService _userService;

        public GetAllAgentsCommandHandler(IBotService botService, IUserService userService)
        {
            _botService = botService;
            _userService = userService;
        }

        public async Task<Dictionary<User, List<Bot>>> Handle(GetAllAgentsCommand request, CancellationToken cancellationToken)
        {
            // Get all users
            var allUsers = await _userService.GetAllUsersAsync();
            
            // Create result dictionary
            var result = new Dictionary<User, List<Bot>>();
            
            // For each user, get their bots
            foreach (var user in allUsers)
            {
                var userBots = await _botService.GetBotsByUser(user.Id);
                var botList = userBots.ToList();
                
                // Apply time filter if specified
                if (request.TimeFilter != "Total")
                {
                    var cutoffDate = GetCutoffDate(request.TimeFilter);
                    botList = botList.Where(bot => 
                        bot.StartupTime >= cutoffDate || 
                        bot.CreateDate >= cutoffDate).ToList();
                }
                
                result[user] = botList;
            }
            
            return result;
        }

        /// <summary>
        /// Gets the cutoff date based on the time filter
        /// </summary>
        private DateTime GetCutoffDate(string timeFilter)
        {
            return timeFilter switch
            {
                "24H" => DateTime.UtcNow.AddHours(-24),
                "3D" => DateTime.UtcNow.AddDays(-3),
                "1W" => DateTime.UtcNow.AddDays(-7),
                "1M" => DateTime.UtcNow.AddMonths(-1),
                "1Y" => DateTime.UtcNow.AddYears(-1),
                _ => DateTime.MinValue // Default to include all data
            };
        }
    }
} 