using Microsoft.AspNetCore.Mvc; using api.Services; using api.DTOs; using Microsoft.EntityFrameworkCore; using api.RabbitMQ; namespace api.Controllers { [ApiController] [Route("api/[controller]")] public class PersonController(IPersonService personService, IMessageProducer messagePublisher) : ControllerBase { private readonly IPersonService _personService = personService; private readonly IMessageProducer _messagePublisher = messagePublisher; [HttpGet] public async Task GetAll() { var persons = await _personService.GetAllPersonsAsync(); return Ok(persons); } [HttpGet("username/{username}")] public async Task GetByUsername(string username) { try { var person = await _personService.GetPersonByUsernameAsync(username); return Ok(person); } catch (KeyNotFoundException) { return NotFound(); } } [HttpPost] public async Task Add(PersonDto personDto) { try { await _personService.AddPersonAsync(personDto); _messagePublisher.SendMessage(personDto); return CreatedAtAction(nameof(GetByUsername), new { username = personDto.Username }, personDto); } catch (ArgumentException ex) { return BadRequest(ex.Message); } catch (DbUpdateException) { return Conflict("Username already exists"); } } [HttpPut("username/{username}")] public async Task Update(string username, PersonDto personDto) { try { await _personService.UpdatePersonAsync(username, personDto); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } } [HttpDelete("username/{username}")] public async Task Delete(string username) { try { await _personService.DeletePersonAsync(username); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } } } }