using Managing.Application.Abstractions;
using Managing.Application.ManageBot.Commands;
using MediatR;

namespace Managing.Application.ManageBot
{
    /// <summary>
    /// Handler for updating trading bot configurations
    /// </summary>
    public class UpdateBotConfigCommandHandler : IRequestHandler<UpdateBotConfigCommand, string>
    {
        private readonly IBotService _botService;

        public UpdateBotConfigCommandHandler(IBotService botService)
        {
            _botService = botService;
        }

        public async Task<string> Handle(UpdateBotConfigCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Identifier))
                {
                    throw new ArgumentException("Bot identifier is required");
                }

                if (request.NewConfig == null)
                {
                    throw new ArgumentException("New configuration is required");
                }

                // Get the bot from active bots
                var activeBots = _botService.GetActiveBots();
                var bot = activeBots.FirstOrDefault(b => b.Identifier == request.Identifier);

                if (bot == null)
                {
                    return $"Bot with identifier {request.Identifier} not found or is not running";
                }

                // Update the bot configuration
                var updateResult = await bot.UpdateConfiguration(request.NewConfig);

                if (updateResult)
                {
                    return $"Bot configuration updated successfully for {request.Identifier}";
                }
                else
                {
                    return $"Failed to update bot configuration for {request.Identifier}";
                }
            }
            catch (Exception ex)
            {
                return $"Error updating bot configuration: {ex.Message}";
            }
        }
    }
} 