using Managing.Application.Abstractions;
using Managing.Application.ManageBot.Commands;
using MediatR;
using Microsoft.Extensions.Logging;
using static Managing.Common.Enums;

namespace Managing.Application.ManageBot
{
    public class StopAllUserBotsCommandHandler : IRequestHandler<StopAllUserBotsCommand, bool>
    {
        private readonly IBotService _botService;
        private readonly ILogger<StopAllUserBotsCommandHandler> _logger;

        public StopAllUserBotsCommandHandler(IBotService botService, ILogger<StopAllUserBotsCommandHandler> logger)
        {
            _botService = botService;
            _logger = logger;
        }

        public async Task<bool> Handle(StopAllUserBotsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // Get all bots for the user
                var userBots = await _botService.GetBotsByUser(request.User.Id);
                
                // Filter only active bots (status Up)
                var activeBots = userBots.Where(bot => bot.Status == BotStatus.Running).ToList();
                
                if (!activeBots.Any())
                {
                    _logger.LogInformation("No active bots found for user {UserName}", request.User.Name);
                    return true;
                }

                _logger.LogInformation("Stopping {BotCount} active bots for user {UserName}", 
                    activeBots.Count, request.User.Name);

                // Stop each active bot
                var stopTasks = activeBots.Select(bot => _botService.StopBot(bot.Identifier));
                await Task.WhenAll(stopTasks);

                _logger.LogInformation("Successfully stopped {BotCount} bots for user {UserName}", 
                    activeBots.Count, request.User.Name);

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error stopping all bots for user {UserName}", request.User.Name);
                return false;
            }
        }
    }
} 