using System; using System.Threading; using System.Threading.Tasks; using AutoMapper; using InternshipSystem.Api.Queries; using InternshipSystem.Api.Security; using InternshipSystem.Core; using InternshipSystem.Repository; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace InternshipSystem.Api.Services { public class InternshipService : IInternshipService { private readonly InternshipDbContext _context; private IMapper Mapper { get; } public InternshipService(InternshipDbContext context, IMapper mapper) { _context = context; Mapper = mapper; } public async Task AddDocumentToInternship(DocumentPublishRequest documentRequest, User user, CancellationToken cancellationToken) { var edition = await _context.Editions.FindAsync(user.EditionId); var internship = await _context.Entry(edition) .Collection(e => e.Internships) .Query() .Include(i => i.Documentation) .SingleAsync(i => i.Student.Id == user.PersonNumber, cancellationToken); var document = Mapper.Map(documentRequest); if (documentRequest.Id.HasValue) { try { internship.UpdateDocument(document); } catch (InvalidOperationException) { return new NotFoundResult(); } } else { internship.AddNewDocument(document); } await _context.SaveChangesAsync(cancellationToken); return new OkResult(); } } }