using GestionIntegral.Api.Dtos.Distribucion;
using GestionIntegral.Api.Services.Distribucion;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace GestionIntegral.Api.Controllers.Distribucion
{
    [Route("api/[controller]")] // Ruta base: /api/salidasotrosdestinos
    [ApiController]
    [Authorize]
    public class SalidasOtrosDestinosController : ControllerBase
    {
        private readonly ISalidaOtroDestinoService _salidaService;
        private readonly ILogger<SalidasOtrosDestinosController> _logger;

        // Permisos para Salidas Otros Destinos (SO001 a SO003, asumiendo OD00X para la entidad OtrosDestinos)
        private const string PermisoVerSalidasOD = "SO001";
        private const string PermisoCrearSalidaOD = "SO002"; // Asumo SO002 para crear/modificar basado en tu excel
        private const string PermisoModificarSalidaOD = "SO002"; // "
        private const string PermisoEliminarSalidaOD = "SO003";

        public SalidasOtrosDestinosController(ISalidaOtroDestinoService salidaService, ILogger<SalidasOtrosDestinosController> logger)
        {
            _salidaService = salidaService;
            _logger = logger;
        }

        private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
        private int? GetCurrentUserId()
        {
            if (int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"), out int userId)) return userId;
            _logger.LogWarning("No se pudo obtener el UserId del token JWT en SalidasOtrosDestinosController.");
            return null;
        }

        // GET: api/salidasotrosdestinos
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<SalidaOtroDestinoDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetAllSalidas(
            [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
            [FromQuery] int? idPublicacion, [FromQuery] int? idDestino)
        {
            if (!TienePermiso(PermisoVerSalidasOD)) return Forbid();
            var salidas = await _salidaService.ObtenerTodosAsync(fechaDesde, fechaHasta, idPublicacion, idDestino);
            return Ok(salidas);
        }

        // GET: api/salidasotrosdestinos/{idParte}
        [HttpGet("{idParte:int}", Name = "GetSalidaOtroDestinoById")]
        [ProducesResponseType(typeof(SalidaOtroDestinoDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetSalidaOtroDestinoById(int idParte)
        {
            if (!TienePermiso(PermisoVerSalidasOD)) return Forbid();
            var salida = await _salidaService.ObtenerPorIdAsync(idParte);
            if (salida == null) return NotFound();
            return Ok(salida);
        }

        // POST: api/salidasotrosdestinos
        [HttpPost]
        [ProducesResponseType(typeof(SalidaOtroDestinoDto), StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> CreateSalidaOtroDestino([FromBody] CreateSalidaOtroDestinoDto createDto)
        {
            if (!TienePermiso(PermisoCrearSalidaOD)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (dto, error) = await _salidaService.CrearAsync(createDto, userId.Value);
            if (error != null) return BadRequest(new { message = error });
            if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar la salida.");
            return CreatedAtRoute("GetSalidaOtroDestinoById", new { idParte = dto.IdParte }, dto);
        }

        // PUT: api/salidasotrosdestinos/{idParte}
        [HttpPut("{idParte:int}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateSalidaOtroDestino(int idParte, [FromBody] UpdateSalidaOtroDestinoDto updateDto)
        {
            if (!TienePermiso(PermisoModificarSalidaOD)) return Forbid(); // O SO002 si se usa para modificar
            if (!ModelState.IsValid) return BadRequest(ModelState);
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _salidaService.ActualizarAsync(idParte, updateDto, userId.Value);
            if (!exito)
            {
                if (error == "Registro de salida no encontrado.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

        // DELETE: api/salidasotrosdestinos/{idParte}
        [HttpDelete("{idParte:int}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteSalidaOtroDestino(int idParte)
        {
            if (!TienePermiso(PermisoEliminarSalidaOD)) return Forbid();
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _salidaService.EliminarAsync(idParte, userId.Value);
            if (!exito)
            {
                if (error == "Registro de salida no encontrado.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }
}