using System.Net; using DTO; using Entity; using Microsoft.AspNetCore.Mvc; using Shared; namespace WfApi.Controllers { [Route("api/v1/source")] [ApiController] public class SourceController : ControllerBase { private readonly ISourceService _source; private readonly ILogger _logger; public SourceController(ISourceService sourceService, ILogger logger) { _source = sourceService; _logger = logger; } [HttpGet("{id}")] // Indiquer que l'id est dans l'URL [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetSource(int id) { try { var source = await _source.GetSourceById(id); if(source != null) { return Ok(source); } else { return NoContent(); } } catch(Exception e) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); } } [HttpGet("all")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetAllSource(int index = 0, int count = 10) { try { var result = await _source.GetSomesSource(index, count); if (result != null) { return await Task.FromResult(Ok(result)); } else { return NoContent(); } } catch (Exception e) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); } } [HttpPost] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task CreateSource([FromBody] SourceDTO newSource) { try { if(newSource == null) { return BadRequest(new { message = "Source data is required." }); } try { var existingSource = await _source.GetSourceById(newSource.Id); return Conflict(new { message = "A source with this ID already exists." }); } catch(KeyNotFoundException e) { await _source.AddSource(newSource); return CreatedAtAction(nameof(GetAllSource), new { id = newSource.Id }, newSource); } } catch (Exception e) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); } } [HttpPut()] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task UpdateSource([FromQuery] int id, [FromBody] SourceDTO updatedSource) { try { if (updatedSource == null) { return BadRequest(new { message = "new source data is required." }); } var result = _source.UpdateSource(id, updatedSource); return Ok(result); } catch (Exception e) { return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); } } } }