using System.Net; using DTO; using Entity; using Microsoft.AspNetCore.Mvc; using Shared; namespace WfApi.Controllers { [ApiController] [Route("api/v1/commentary")] //Version API public class CommentariesController : ControllerBase { private readonly ICommentaryService _commentary; private readonly ILogger _logger; public CommentariesController(ICommentaryService commentaryService, ILogger logger) { _commentary = commentaryService; _logger = logger; } [HttpGet("{id}")] // Indiquer que l'id est dans l'URL public async Task GetCommentary(int id, int index = 0, int count = 5) { try { var result =await _commentary.GetCommentaryByQuote(id, index, count); if (result != null) { return await Task.FromResult(Ok(result)); } else { return NoContent(); } } catch (Exception) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); } } [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task CreateCommentary([FromBody] CommentaryDTO newCommentary, int idQuote) { try { if (newCommentary == null) { return BadRequest(new { message = "Comment data is required." }); } try { var existingCommentary = await _commentary.GetCommentaryById(newCommentary.Id); return Conflict(new { message = "A comment with this ID already exists." }); } catch (KeyNotFoundException e) { await _commentary.AddComment(newCommentary, idQuote); return CreatedAtAction(nameof(GetCommentary), new { id = newCommentary.Id }, newCommentary); } } catch (Exception) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." }); } } [HttpDelete] // /api/v1/commentary?id=51 [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task DeleteCommentary([FromQuery] int id) { try { var existingCommentary = _commentary.GetCommentaryById(id).Result; if (existingCommentary == null) { return NotFound(new { message = "Commentary not found." }); } await _commentary.RemoveCommentary(existingCommentary.Id); return Ok(new { message = $"Commentary {id} deleted successfully." }); } catch (Exception) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); } } } }