using adas_core.Application.Exceptions;
using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Attributes;
using adas_core.Authentication.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.Masters;
using Microsoft.AspNetCore.Mvc;

namespace adas_core.Controllers;

[Route("Box")]
[ApiController]
public class BoxController : ControllerBase
{
    private readonly IUnitService _unitService;
    private readonly IPatientService _patientService;
    private readonly IMasterListService<InsulationList> _isulationListService;
    private readonly IPointOfCareService _pointOfCareService;
    private readonly IUserService _userService;

    public BoxController(IUnitService unitService, IPatientService patientService, IMasterListService<InsulationList> isulationListService, IPointOfCareService pointOfCareService, IUserService userService)
    {
        _unitService = unitService;
        _patientService = patientService;
        _isulationListService = isulationListService;
        _pointOfCareService = pointOfCareService;
        _userService = userService;
    }

    [HttpGet("{boxNumber}/{elementSwitjAction}/switch-data")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    public async Task<IActionResult> SwitchData(string boxNumber, string elementSwitjAction)
    {
        // Necesito buscar el por el boxNumber la unidad a la que pertenece 
        // Encontrar la lista que actua sobre la observacion que quiero cambiar en base al action
        // Enviar un valor aleatorio diferente del que este en uso
        var userNameContext = HttpContext.User.Identity?.Name ??
                              throw new UnauthorizedException(HttpEnum.ErrorMessage.UnauthorizedNoPermission);
        var user = await _userService.GetUserByUserName(userNameContext);
        var unit = await _unitService.FindByUnitNameOrPocName(null, boxNumber);
        switch (elementSwitjAction)
        {
            case "Isolation":
                var list = await _isulationListService.GetMasterListById(unit!.InsulationListId!.Value, null);
                var option = list!.Options[Random.Shared.Next(list.Options.Count)];                
                var poc = await _pointOfCareService.FindByBedAndUnitId(boxNumber, unit.Id);
                var data = await _pointOfCareService.GetInfo(poc!.Id, null, true);
                var options = new List<OptionList>
                {
                    new()
                    {
                        Id = option.Id,
                        Name = option.Name,
                        Color = option.Color,
                        BgColor = option.BgColor,
                    }
                };
                await _patientService.UpdatePatientMasterList(data!.Patient!.Id, MasterListType.InsulationList, options, user, options);

                
                break;
            case "Mobility":
                break;
        }
        return Ok();
    }
}