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/ajustes")]
    [ApiController]
    [Authorize]
    public class AjustesController : ControllerBase
    {
        private readonly IAjusteService _ajusteService;
        private readonly ILogger<AjustesController> _logger;

        // Permiso a crear en BD
        private const string PermisoGestionarAjustes = "SU011";

        public AjustesController(IAjusteService ajusteService, ILogger<AjustesController> logger)
        {
            _ajusteService = ajusteService;
            _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;
            return null;
        }

        // GET: api/suscriptores/{idSuscriptor}/ajustes
        [HttpGet("~/api/suscriptores/{idSuscriptor:int}/ajustes")]
        [ProducesResponseType(typeof(IEnumerable<AjusteDto>), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetAjustesPorSuscriptor(int idSuscriptor, [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta)
        {
            if (!TienePermiso(PermisoGestionarAjustes)) return Forbid();
            var ajustes = await _ajusteService.ObtenerAjustesPorSuscriptor(idSuscriptor, fechaDesde, fechaHasta);
            return Ok(ajustes);
        }

        // POST: api/ajustes
        [HttpPost]
        [ProducesResponseType(typeof(AjusteDto), StatusCodes.Status201Created)]
        public async Task<IActionResult> CreateAjuste([FromBody] CreateAjusteDto createDto)
        {
            if (!TienePermiso(PermisoGestionarAjustes)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);

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

            var (dto, error) = await _ajusteService.CrearAjusteManual(createDto, userId.Value);

            if (error != null) return BadRequest(new { message = error });
            if (dto == null) return StatusCode(500, "Error al crear el ajuste.");

            // Devolvemos el objeto creado con un 201
            return StatusCode(201, dto);
        }

        // POST: api/ajustes/{id}/anular
        [HttpPost("{id:int}/anular")]
        public async Task<IActionResult> Anular(int id)
        {
            if (!TienePermiso(PermisoGestionarAjustes)) return Forbid();
            var userId = GetCurrentUserId();
            if (userId == null) return Unauthorized();

            var (exito, error) = await _ajusteService.AnularAjuste(id, userId.Value);
            if (!exito) return BadRequest(new { message = error });

            return Ok(new { message = "Ajuste anulado correctamente." });
        }

        // PUT: api/ajustes/{id}
        [HttpPut("{id:int}")]
        public async Task<IActionResult> UpdateAjuste(int id, [FromBody] UpdateAjusteDto updateDto)
        {
            if (!TienePermiso(PermisoGestionarAjustes)) return Forbid();
            if (!ModelState.IsValid) return BadRequest(ModelState);

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