using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RobotNet.RobotManager.Services;
using RobotNet.RobotManager.Services.Traffic;
using RobotNet.RobotShares.Dtos;
using RobotNet.RobotShares.Models;
using RobotNet.Shares;

namespace RobotNet.RobotManager.Controllers;

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TrafficManagerController(TrafficManager TrafficManager, LoggerController<TrafficManagerController> Logger) : ControllerBase
{
    [HttpPut]
    public MessageResult UpdateLocker(UpdateAgentLockerModel model)
    {
        try
        {
            if (TrafficManager.TrafficMaps.TryGetValue(model.MapId, out TrafficMap? trafficmap) && trafficmap is not null)
            {
                trafficmap.UpdateLocker(model.AgentId, [.. model.LockedNodes]);
            }
            return new(true);
        }
        catch (Exception ex)
        {
            Logger.Warning($"UpdateLocker: Hệ thống có lỗi xảy ra - {ex.Message}");
            return new(false, $"Hệ thống có lỗi xảy ra");
        }
    }

    [HttpDelete]
    [Route("{mapId}/{robotId}")]
    public MessageResult DeleteAgent([FromRoute] Guid mapId, [FromRoute] string robotId)
    {
        try
        {
            if (TrafficManager.TrafficMaps.TryGetValue(mapId, out TrafficMap? trafficmap) && trafficmap is not null)
            {
                trafficmap.Locked.Remove(robotId);
            }
            return TrafficManager.DeleteAgent(robotId);
        }
        catch (Exception ex)
        {
            Logger.Warning($"DeleteAgent: Hệ thống có lỗi xảy ra - {ex.Message}");
            return new(false, $"Hệ thống có lỗi xảy ra");
        }
    }
}
