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

namespace GestionIntegral.Api.Controllers.Distribucion
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class CanillasController : ControllerBase
    {
        private readonly ICanillaService _canillaService;
        private readonly ILogger<CanillasController> _logger;

        // Permisos para Canillas (CG001 a CG005)
        private const string PermisoVer = "CG001";
        private const string PermisoCrear = "CG002";
        private const string PermisoModificar = "CG003";
        // CG004 es para Porcentajes, se manejará en un endpoint específico o en Update si se incluye en DTO
        private const string PermisoBaja = "CG005"; // Para dar de baja/alta

        public CanillasController(ICanillaService canillaService, ILogger<CanillasController> logger)
        {
            _canillaService = canillaService;
            _logger = logger;
        }

        private bool TienePermiso(string codAccRequerido)
        {
            if (User.IsInRole("SuperAdmin")) return true;
            return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido);
        }

        private int? GetCurrentUserId()
        {
            var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
            if (int.TryParse(userIdClaim, out int userId)) return userId;
            return null;
        }

        // GET: api/canillas
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<CanillaDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetAllCanillas([FromQuery] string? nomApe, [FromQuery] int? legajo, [FromQuery] bool? esAccionista, [FromQuery] bool? soloActivos = true)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var canillitas = await _canillaService.ObtenerTodosAsync(nomApe, legajo, soloActivos, esAccionista);
            return Ok(canillitas);
        }

        [HttpGet("dropdown")]
        [ProducesResponseType(typeof(IEnumerable<CanillaDropdownDto>), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetAllDropdownCanillas([FromQuery] bool? esAccionista, [FromQuery] bool? soloActivos = true)
        {
            var canillitas = await _canillaService.ObtenerTodosDropdownAsync(esAccionista, soloActivos);
            return Ok(canillitas);
        }


        // GET: api/canillas/{id}
        [HttpGet("{id:int}", Name = "GetCanillaById")]
        [ProducesResponseType(typeof(CanillaDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetCanillaById(int id)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var canilla = await _canillaService.ObtenerPorIdAsync(id);
            if (canilla == null) return NotFound();
            return Ok(canilla);
        }

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

            var (canillaCreado, error) = await _canillaService.CrearAsync(createDto, idUsuario.Value);
            if (error != null) return BadRequest(new { message = error });
            if (canillaCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el canillita.");

            return CreatedAtRoute("GetCanillaById", new { id = canillaCreado.IdCanilla }, canillaCreado);
        }

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

            var (exito, error) = await _canillaService.ActualizarAsync(id, updateDto, idUsuario.Value);
            if (!exito)
            {
                if (error == "Canillita no encontrado.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

        // POST: api/canillas/{id}/toggle-baja
        [HttpPost("{id:int}/toggle-baja")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> ToggleBajaCanilla(int id, [FromBody] ToggleBajaCanillaDto bajaDto)
        {
            if (!TienePermiso(PermisoBaja)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);
            var idUsuario = GetCurrentUserId();
            if (idUsuario == null) return Unauthorized();

            var (exito, error) = await _canillaService.ToggleBajaAsync(id, bajaDto.DarDeBaja, idUsuario.Value);
            if (!exito)
            {
                if (error == "Canillita no encontrado.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }
}