using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using InternshipSystem.Api.Queries;
using InternshipSystem.Api.Security;
using InternshipSystem.Core;
using InternshipSystem.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace InternshipSystem.Api.Controllers
{
[ApiController]
[Route("document")]
public class DocumentsController : ControllerBase
{
private InternshipDbContext Context { get; }
private IMapper Mapper { get; }
public DocumentsController(InternshipDbContext context, IMapper mapper)
{
Context = context;
Mapper = mapper;
}
///
/// Fill out required document,
///
/// Documents Scan and description, and Id of filled document
///
/// If change was successfully registered
/// If the provided query was malformed
/// Id doesn't match any required document
/// This action is only available for authorized student registered for current edition
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[Authorize(Policy = Policies.RegisteredOnly)]
public async Task AddDocumentToInternship([FromBody] DocumentPublishRequest documentRequest, User user)
{
var validator = new DocumentPublishRequest.Validator();
var validationResult = await validator.ValidateAsync(documentRequest);
if (!validationResult.IsValid)
{
return BadRequest(validationResult.ToString());
}
var edition =
await Context.Editions
.FindAsync(user.EditionId.Value);
var internship = await Context.Entry(edition)
.Collection(e => e.Internships)
.Query()
.SingleAsync(i => i.Student.Id == user.PersonNumber);
var document = Mapper.Map(documentRequest);
if (documentRequest.Id.HasValue)
{
try
{
internship.UpdateDocument(document);
}
catch (InvalidOperationException)
{
return NotFound();
}
}
else
{
internship.AddNewDocument(document);
}
await Context.SaveChangesAsync();
return Ok();
}
}
}