using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.ManageBot.Commands;
using MediatR;
using static Managing.Common.Enums;

namespace Managing.Application.ManageBot
{
    /// <summary>
    /// Handler for retrieving all agent statuses
    /// </summary>
    public class GetAgentStatusesCommandHandler : IRequestHandler<GetAgentStatusesCommand, List<AgentStatusResponse>>
    {
        private readonly IBotService _botService;
        private readonly IAccountService _accountService;

        public GetAgentStatusesCommandHandler(IBotService botService, IAccountService accountService)
        {
            _botService = botService;
            _accountService = accountService;
        }

        public async Task<List<AgentStatusResponse>> Handle(GetAgentStatusesCommand request,
            CancellationToken cancellationToken)
        {
            var result = new List<AgentStatusResponse>();
            var allActiveBots = await _botService.GetBotsByStatusAsync(BotStatus.Running);

            // Group bots by user and determine status
            var agentGroups = allActiveBots
                .Where(bot => bot.User != null)
                .GroupBy(bot => bot.User)
                .ToList();

            foreach (var agentGroup in agentGroups)
            {
                var user = agentGroup.Key;
                var bots = agentGroup.ToList();

                // Determine agent status: Online if at least one strategy is running, Offline otherwise
                var agentStatus = bots.Any(bot => bot.Status == BotStatus.Running)
                    ? AgentStatus.Online
                    : AgentStatus.Offline;

                result.Add(new AgentStatusResponse
                {
                    AgentName = user.AgentName,
                    Status = agentStatus
                });
            }

            return result;
        }
    }
}