using GestionIntegral.Api.Dtos.Contables;
using GestionIntegral.Api.Services.Contables;
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.Contables
{
    [Route("api/notascreditodebito")] // Ruta base
    [ApiController]
    [Authorize]
    public class NotasCreditoDebitoController : ControllerBase
    {
        private readonly INotaCreditoDebitoService _notaService;
        private readonly ILogger<NotasCreditoDebitoController> _logger;

        // Permisos para Notas C/D (CN001 a CN004)
        private const string PermisoVer = "CN001";
        private const string PermisoCrear = "CN002";
        private const string PermisoModificar = "CN003";
        private const string PermisoEliminar = "CN004";

        public NotasCreditoDebitoController(INotaCreditoDebitoService notaService, ILogger<NotasCreditoDebitoController> logger)
        {
            _notaService = notaService;
            _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 NotasCreditoDebitoController.");
            return null;
        }

        // GET: api/notascreditodebito
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<NotaCreditoDebitoDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetAll(
            [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
            [FromQuery] string? destino, [FromQuery] int? idDestino,
            [FromQuery] int? idEmpresa, [FromQuery] string? tipoNota)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var notas = await _notaService.ObtenerTodosAsync(fechaDesde, fechaHasta, destino, idDestino, idEmpresa, tipoNota);
            return Ok(notas);
        }

        // GET: api/notascreditodebito/{idNota}
        [HttpGet("{idNota:int}", Name = "GetNotaCreditoDebitoById")]
        [ProducesResponseType(typeof(NotaCreditoDebitoDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetById(int idNota)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var nota = await _notaService.ObtenerPorIdAsync(idNota);
            if (nota == null) return NotFound(new { message = $"Nota con ID {idNota} no encontrada." });
            return Ok(nota);
        }

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

            var (dto, error) = await _notaService.CrearAsync(createDto, userId.Value);
            if (error != null) return BadRequest(new { message = error });
            if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar la nota.");
            
            return CreatedAtRoute("GetNotaCreditoDebitoById", new { idNota = dto.IdNota }, dto);
        }

        // PUT: api/notascreditodebito/{idNota}
        [HttpPut("{idNota:int}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> Update(int idNota, [FromBody] UpdateNotaDto updateDto)
        {
            if (!TienePermiso(PermisoModificar)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _notaService.ActualizarAsync(idNota, updateDto, userId.Value);
            if (!exito)
            {
                if (error == "Nota no encontrada.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

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

            var (exito, error) = await _notaService.EliminarAsync(idNota, userId.Value);
            if (!exito)
            {
                if (error == "Nota no encontrada.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }
}