using GestionIntegral.Api.Dtos.Suscripciones;
using GestionIntegral.Api.Services.Suscripciones;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace GestionIntegral.Api.Controllers.Suscripciones
{
    [Route("api/suscriptores")]
    [ApiController]
    [Authorize]
    public class SuscriptoresController : ControllerBase
    {
        private readonly ISuscriptorService _suscriptorService;
        private readonly ILogger<SuscriptoresController> _logger;

        // Permisos para Suscriptores
        private const string PermisoVer = "SU001";
        private const string PermisoCrear = "SU002";
        private const string PermisoModificar = "SU003";
        private const string PermisoActivarDesactivar = "SU004";

        public SuscriptoresController(ISuscriptorService suscriptorService, ILogger<SuscriptoresController> logger)
        {
            _suscriptorService = suscriptorService;
            _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 SuscriptoresController.");
            return null;
        }

        // GET: api/suscriptores
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<SuscriptorDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetAll([FromQuery] string? nombre, [FromQuery] string? nroDoc, [FromQuery] bool soloActivos = true)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var suscriptores = await _suscriptorService.ObtenerTodos(nombre, nroDoc, soloActivos);
            return Ok(suscriptores);
        }

        // GET: api/suscriptores/{id}
        [HttpGet("{id:int}", Name = "GetSuscriptorById")]
        [ProducesResponseType(typeof(SuscriptorDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetById(int id)
        {
            if (!TienePermiso(PermisoVer)) return Forbid();
            var suscriptor = await _suscriptorService.ObtenerPorId(id);
            if (suscriptor == null) return NotFound();
            return Ok(suscriptor);
        }

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

            var (dto, error) = await _suscriptorService.Crear(createDto, userId.Value);
            
            if (error != null) return BadRequest(new { message = error });
            if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el suscriptor.");
            
            return CreatedAtRoute("GetSuscriptorById", new { id = dto.IdSuscriptor }, dto);
        }

        // PUT: api/suscriptores/{id}
        [HttpPut("{id:int}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> Update(int id, [FromBody] UpdateSuscriptorDto updateDto)
        {
            if (!TienePermiso(PermisoModificar)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);

            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _suscriptorService.Actualizar(id, updateDto, userId.Value);
            
            if (!exito)
            {
                if (error != null && error.Contains("no encontrado")) return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

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

            var (exito, error) = await _suscriptorService.Desactivar(id, userId.Value);
            
            if (!exito)
            {
                if (error != null && error.Contains("no encontrado")) return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

        // POST: api/suscriptores/{id}/activar
        [HttpPost("{id:int}/activar")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> Activate(int id)
        {
            if (!TienePermiso(PermisoActivarDesactivar)) return Forbid();
            
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _suscriptorService.Activar(id, userId.Value);
            
            if (!exito)
            {
                if (error != null && error.Contains("no encontrado")) return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }
}