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/facturacion")] [ApiController] [Authorize] public class FacturacionController : ControllerBase { private readonly IFacturacionService _facturacionService; private readonly ILogger _logger; // Permiso para generar facturación (a crear en la BD) private const string PermisoGenerarFacturacion = "SU006"; public FacturacionController(IFacturacionService facturacionService, ILogger logger) { _facturacionService = facturacionService; _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; } // POST: api/facturacion/{anio}/{mes} [HttpPost("{anio:int}/{mes:int}")] public async Task GenerarFacturacion(int anio, int mes) { if (!TienePermiso(PermisoGenerarFacturacion)) return Forbid(); var userId = GetCurrentUserId(); if (userId == null) return Unauthorized(); if (anio < 2020 || mes < 1 || mes > 12) { return BadRequest(new { message = "El año y el mes proporcionados no son válidos." }); } var (exito, mensaje, facturasGeneradas) = await _facturacionService.GenerarFacturacionMensual(anio, mes, userId.Value); if (!exito) { return StatusCode(StatusCodes.Status500InternalServerError, new { message = mensaje }); } return Ok(new { message = mensaje, facturasGeneradas }); } // GET: api/facturacion/{anio}/{mes} [HttpGet("{anio:int}/{mes:int}")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task GetFacturas(int anio, int mes) { // Usamos el permiso de generar facturación también para verlas. if (!TienePermiso(PermisoGenerarFacturacion)) return Forbid(); if (anio < 2020 || mes < 1 || mes > 12) { return BadRequest(new { message = "El período no es válido." }); } var facturas = await _facturacionService.ObtenerFacturasPorPeriodo(anio, mes); return Ok(facturas); } // POST: api/facturacion/{idFactura}/enviar-email [HttpPost("{idFactura:int}/enviar-email")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task EnviarEmail(int idFactura) { // Usaremos un nuevo permiso para esta acción if (!TienePermiso("SU009")) return Forbid(); var (exito, error) = await _facturacionService.EnviarFacturaPorEmail(idFactura); if (!exito) { return BadRequest(new { message = error }); } return Ok(new { message = "Email enviado a la cola de procesamiento." }); } } }