using GestionIntegral.Api.Dtos.Impresion; // Para los DTOs using GestionIntegral.Api.Services.Impresion; // Para IPlantaService using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace GestionIntegral.Api.Controllers.Impresion { [Route("api/[controller]")] // Ruta base: /api/plantas [ApiController] [Authorize] // Requiere autenticación para todos los endpoints public class PlantasController : ControllerBase { private readonly IPlantaService _plantaService; private readonly ILogger _logger; public PlantasController(IPlantaService plantaService, ILogger logger) { _plantaService = plantaService ?? throw new ArgumentNullException(nameof(plantaService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } // --- Helper para verificar permisos --- private bool TienePermiso(string codAccRequerido) { if (User.IsInRole("SuperAdmin")) return true; return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido); } // --- Helper para obtener User ID --- private int? GetCurrentUserId() { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); if (int.TryParse(userIdClaim, out int userId)) { return userId; } _logger.LogWarning("No se pudo obtener el UserId del token JWT en PlantasController."); return null; } // --- Endpoints CRUD --- // GET: api/plantas // Permiso: IP001 (Ver Plantas) [HttpGet] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetAllPlantas([FromQuery] string? nombre, [FromQuery] string? detalle) { if (!TienePermiso("IP001")) { _logger.LogWarning("Acceso denegado a GetAllPlantas para el usuario {UserId}", GetCurrentUserId() ?? 0); return Forbid(); } try { var plantas = await _plantaService.ObtenerTodasAsync(nombre, detalle); return Ok(plantas); } catch (Exception ex) { _logger.LogError(ex, "Error al obtener todas las Plantas. Filtros: Nombre={Nombre}, Detalle={Detalle}", nombre, detalle); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener las plantas."); } } // GET: api/plantas/dropdown [HttpGet("dropdown")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] // NO chequeo TienePermiso("IP001")(requiere autenticación) public async Task GetPlantasForDropdown() { try { var plantas = await _plantaService.ObtenerParaDropdownAsync(); return Ok(plantas); } catch (Exception ex) { _logger.LogError(ex, "Error al obtener plantas para dropdown."); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener plantas para selección."); } } // GET: api/plantas/{id} // Permiso: IP001 (Ver Plantas) [HttpGet("{id:int}", Name = "GetPlantaById")] [ProducesResponseType(typeof(PlantaDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetPlantaById(int id) { if (!TienePermiso("IP001")) return Forbid(); try { var planta = await _plantaService.ObtenerPorIdAsync(id); if (planta == null) { return NotFound(new { message = $"Planta con ID {id} no encontrada." }); } return Ok(planta); } catch (Exception ex) { _logger.LogError(ex, "Error al obtener Planta por ID: {Id}", id); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener la planta."); } } // POST: api/plantas // Permiso: IP002 (Agregar Plantas) [HttpPost] [ProducesResponseType(typeof(PlantaDto), StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task CreatePlanta([FromBody] CreatePlantaDto createDto) { if (!TienePermiso("IP002")) return Forbid(); if (!ModelState.IsValid) return BadRequest(ModelState); var idUsuario = GetCurrentUserId(); if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token."); try { var (plantaCreada, error) = await _plantaService.CrearAsync(createDto, idUsuario.Value); if (error != null) return BadRequest(new { message = error }); if (plantaCreada == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear la planta."); return CreatedAtRoute("GetPlantaById", new { id = plantaCreada.IdPlanta }, plantaCreada); } catch (Exception ex) { _logger.LogError(ex, "Error al crear Planta. Nombre: {Nombre} por Usuario ID: {UsuarioId}", createDto.Nombre, idUsuario); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al crear la planta."); } } // PUT: api/plantas/{id} // Permiso: IP003 (Modificar Plantas) [HttpPut("{id:int}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task UpdatePlanta(int id, [FromBody] UpdatePlantaDto updateDto) { if (!TienePermiso("IP003")) return Forbid(); if (!ModelState.IsValid) return BadRequest(ModelState); var idUsuario = GetCurrentUserId(); if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token."); try { var (exito, error) = await _plantaService.ActualizarAsync(id, updateDto, idUsuario.Value); if (!exito) { if (error == "Planta no encontrada.") return NotFound(new { message = error }); return BadRequest(new { message = error }); } return NoContent(); } catch (Exception ex) { _logger.LogError(ex, "Error al actualizar Planta ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar la planta."); } } // DELETE: api/plantas/{id} // Permiso: IP004 (Eliminar Plantas) [HttpDelete("{id:int}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] // Si está en uso [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task DeletePlanta(int id) { if (!TienePermiso("IP004")) return Forbid(); var idUsuario = GetCurrentUserId(); if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token."); try { var (exito, error) = await _plantaService.EliminarAsync(id, idUsuario.Value); if (!exito) { if (error == "Planta no encontrada.") return NotFound(new { message = error }); return BadRequest(new { message = error }); // Ej: "En uso" } return NoContent(); } catch (Exception ex) { _logger.LogError(ex, "Error al eliminar Planta ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al eliminar la planta."); } } } }