using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Retroactiune.Core.Entities; using Retroactiune.Core.Interfaces; using Retroactiune.Core.Services; using Retroactiune.DataTransferObjects; namespace Retroactiune.Controllers { [ApiController] [Route("api/v1/feedback_receivers")] public partial class FeedbackReceiversController : ControllerBase { private readonly IOptions _apiBehaviorOptions; // Note: Probably refactor this to use an Aggregate object, need to learn more about aggregates.. private readonly IFeedbackReceiversService _feedbackReceiversService; private readonly ITokensService _tokensService; private readonly IFeedbacksService _feedbacksService; private readonly IMapper _mapper; private readonly ILogger _logger; public FeedbackReceiversController(IFeedbackReceiversService feedbackReceiversService, ITokensService tokensService, IFeedbacksService feedbacksService, IMapper mapper, IOptions apiBehaviorOptions, ILogger logger) { _feedbackReceiversService = feedbackReceiversService; _tokensService = tokensService; _feedbacksService = feedbacksService; _mapper = mapper; _apiBehaviorOptions = apiBehaviorOptions; _logger = logger; } /// /// Inserts FeedbackReceiver items into the database. /// /// The list of FeedbackReceivers /// A BasicResponse indicating success. /// Returns an ok message. /// If the items is invalid [HttpPost] [ProducesResponseType(typeof(BasicResponse), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task Post([Required] IEnumerable items) { var feedbackReceiversDto = items.ToList(); if (!feedbackReceiversDto.Any()) { ModelState.AddModelError(nameof(IEnumerable), "At least one FeedbackReceiver item is required."); return _apiBehaviorOptions?.Value.InvalidModelStateResponseFactory(ControllerContext); } var mappedItems = feedbackReceiversDto.Select(i => _mapper.Map(i)); await _feedbackReceiversService.CreateManyAsync(mappedItems); return Ok(new BasicResponse() { Message = "Items created successfully!" }); } /// /// Deletes a FeedbackReceiver item from the database. /// /// The guid of the item to be deleted. /// A NoContent result. /// The delete is submitted. /// The request is invalid. [HttpDelete("{guid}")] [ProducesResponseType(typeof(NoContentResult), StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task Delete( [StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)] string guid) { await Task.WhenAll(_feedbackReceiversService.DeleteManyAsync(new[] {guid}), _tokensService.DeleteManyByFeedbackReceiverIdAsync(new[] {guid})); return NoContent(); } /// /// Retrieves a FeedbackReceiver item from the database. /// /// The guid of the item to be retrieved. /// A Ok result with a . /// The item returned successfully. /// The request is invalid. /// The item was not found. [HttpGet("{guid}")] [ProducesResponseType(typeof(FeedbackReceiverOutDto), StatusCodes.Status200OK)] [ProducesResponseType(typeof(BasicResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task Get( [StringLength(24, ErrorMessage = "invalid guid, must be 24 characters", MinimumLength = 24)] string guid) { var result = await _feedbackReceiversService.FindAsync(new[] {guid}); var feedbackReceivers = result as FeedbackReceiver[] ?? result.ToArray(); if (!feedbackReceivers.Any()) { return NotFound(new BasicResponse() { Message = $"Item with guid {guid} was not found." }); } return Ok(feedbackReceivers.First()); } /// /// Retrieves a FeedbackReceiver items from the database. /// /// If set, it will filter results for the given guids. /// If set, it will skip the N items. Allowed range is 1-IntMax. /// If set, it will limit the results to N items. Allowed range is 1-1000. /// A Ok result with a list of . /// The a list is returned. /// The request is invalid. [HttpGet] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(typeof(BasicResponse), StatusCodes.Status400BadRequest)] public async Task List([FromQuery] IEnumerable filter, [RangeAttribute(1, int.MaxValue, ErrorMessage = "offset is out of range, allowed ranges [1-IntMax]"), FromQuery] int offset, [RangeAttribute(1, 1000, ErrorMessage = "limit is out of range, allowed ranges [1-1000]"), FromQuery] int limit) { return Ok(await _feedbackReceiversService.FindAsync(filter, offset, limit)); } /// /// Deletes FeedbackReceiver identified by ids. /// /// A list of FeedbackReceiver ids. /// The request to delete the items has been submitted. /// The request is invalid. /// [HttpDelete] [ProducesResponseType(typeof(NoContentResult), StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(BasicResponse), StatusCodes.Status400BadRequest)] public async Task DeleteMany([Required] IEnumerable ids) { try { var feedbackReceiverIds = ids as string[] ?? ids.ToArray(); await Task.WhenAll(_feedbackReceiversService.DeleteManyAsync(feedbackReceiverIds), _tokensService.DeleteManyByFeedbackReceiverIdAsync(feedbackReceiverIds)); return NoContent(); } catch (GenericServiceException e) { _logger.LogError("{Message}", e.Message); return BadRequest(new BasicResponse { Message = e.Message }); } } } }