using GestionIntegral.Api.Dtos.Radios;
using GestionIntegral.Api.Services.Radios;
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.Radios
{
    [Route("api/[controller]")] // Ruta base: /api/canciones
    [ApiController]
    [Authorize]
    public class CancionesController : ControllerBase
    {
        private readonly ICancionService _cancionService;
        private readonly ILogger<CancionesController> _logger;

        // Asumir permisos para Canciones (ej. RC001-RC004 o usar SS005)
        private const string PermisoVerCanciones = "SS005";
        private const string PermisoGestionarCanciones = "SS005";

        public CancionesController(ICancionService cancionService, ILogger<CancionesController> logger)
        {
            _cancionService = cancionService;
            _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 CancionesController.");
            return null;
        }

        // GET: api/canciones
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<CancionDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetAll([FromQuery] string? tema, [FromQuery] string? interprete, [FromQuery] int? idRitmo)
        {
            if (!TienePermiso(PermisoVerCanciones)) return Forbid();
            var canciones = await _cancionService.ObtenerTodasAsync(tema, interprete, idRitmo);
            return Ok(canciones);
        }

        // GET: api/canciones/{id}
        [HttpGet("{id:int}", Name = "GetCancionById")]
        [ProducesResponseType(typeof(CancionDto), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetById(int id)
        {
            if (!TienePermiso(PermisoVerCanciones)) return Forbid();
            var cancion = await _cancionService.ObtenerPorIdAsync(id);
            if (cancion == null) return NotFound(new { message = $"Canción con ID {id} no encontrada." });
            return Ok(cancion);
        }

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

            var (dto, error) = await _cancionService.CrearAsync(createDto, userId.Value);
            if (error != null) return BadRequest(new { message = error });
            if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear la canción.");
            
            return CreatedAtRoute("GetCancionById", new { id = dto.Id }, dto);
        }

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

            var (exito, error) = await _cancionService.ActualizarAsync(id, updateDto, userId.Value);
            if (!exito)
            {
                if (error == "Canción no encontrada.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }

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

            var (exito, error) = await _cancionService.EliminarAsync(id, userId.Value);
            if (!exito)
            {
                if (error == "Canción no encontrada.") return NotFound(new { message = error });
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }
}