using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Serilog; using YaleAccess.Data; using YaleAccess.Models; namespace YaleAccess.Controllers { [ApiController] [Route("api/[controller]")] [EnableCors] [Authorize] public class PeopleController : ControllerBase { private readonly YaleContext _context; public PeopleController(YaleContext context) { _context = context; } [HttpGet] public async Task GetPeople() { try { // Return all people List people = await _context.People.ToListAsync(); return Ok(new ApiResponse(people)); } catch (Exception ex) { Log.Logger.Error(ex, "An error occured retriving the people."); return BadRequest(new ApiResponse("An error occured retriving the people.")); } } [HttpPost] public async Task CreatePerson([FromBody] Person person) { try { // Create a new person Person newPerson = new() { Name = person.Name, PhoneNumber = person.PhoneNumber }; // Add the person await _context.AddAsync(newPerson); await _context.SaveChangesAsync(); // Return the newly created person return Ok(new ApiResponse(newPerson)); } catch (Exception ex) { Log.Logger.Error(ex, "An error occured creating the person."); return BadRequest(new ApiResponse("An error occured creating the person.")); } } [HttpDelete("{id}")] public async Task DeletePerson([FromRoute] int id) { try { // Ensure the person exists Person person = await _context.People.FindAsync(id) ?? throw new Exception("Person not found."); // Remove the person _context.Remove(person); await _context.SaveChangesAsync(); // Return the newly removed person return Ok(new ApiResponse(person)); } catch (Exception ex) { Log.Logger.Error(ex, "An error occured deletiong the person."); return BadRequest(new ApiResponse("An error occured deletiong the person.")); } } } }