using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using MongoDB.Bson; using server.Models; using server.Persistence.Repositories; namespace server.Controllers.v1 { [ApiController] [ApiVersion("1.0")] [Route("/api/quotes")] [Produces("application/json")] public class QuotesController : ControllerBase { private readonly IQuoteRepository _quoteRepository; public QuotesController(IQuoteRepository quoteRepository) { _quoteRepository = quoteRepository; } /// /// Gets a collection of quotes. /// /// Filter parameters passed from query string. /// Returns the collection of quotes requested. /// Not a valid request. /// Failed to get quotes. /// Returns a collection of quotes. [MapToApiVersion("1.0")] [HttpGet] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task>> GetQuotesAsync([FromQuery] QuoteFilter? filter) { try { var quotes = await _quoteRepository.GetQuotesAsync(filter); return Ok(quotes); } catch (Exception e) { Console.WriteLine(e); return Problem(detail: "Failed to get quotes", statusCode: 500); } } /// /// Gets a quote by its id. /// /// The id of the quote being requested. /// Returns the quote requested. /// Not a valid request. /// Quote with the given id not found. /// Failed to get quote. /// Returns a quote. [MapToApiVersion("1.0")] [HttpGet("{id}")] [ProducesResponseType(typeof(Quote), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] public async Task> GetQuoteByIdAsync(string id) { if (!ObjectId.TryParse(id, out _)) { ModelState.AddModelError(nameof(id), $"{id} is not a valid id"); return ValidationProblem(); } try { var quote = await _quoteRepository.GetQuoteByIdAsync(id); return quote == null ? Problem(detail: $"Could not find quote {id}", statusCode: 404) : Ok(quote); } catch (Exception e) { Console.WriteLine(e); return Problem(detail: "Failed to get quote", statusCode: 500); } } } }