using System;
using System.Threading;
using System.Threading.Tasks;
using InternshipSystem.Api.Security;
using InternshipSystem.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace InternshipSystem.Api.Controllers
{
    [ApiController]
    [Route("register")]
    public class RegistrationController : ControllerBase
    {
        private readonly InternshipDbContext _context;

        public RegistrationController(InternshipDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Register student for edition using provided registration code
        /// </summary>
        /// <param name="registrationCode">GUID of edition </param>
        /// <returns></returns>
        /// <response code="200">If the student was successfully registered</response>
        /// <response code="400">If the provided registration code was malformed</response>
        /// <response code="404">The registration code doesn't match any open edition</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [Authorize]
        public async Task<IActionResult> RegisterStudentForEdition([FromBody] Guid registrationCode, [FromServices] User user, CancellationToken token)
        {
            var edition = await _context.Editions
                .Include(e => e.Internships)
                .FirstOrDefaultAsync(e => e.Id.Equals(registrationCode), cancellationToken: token);

            if (edition == null)
            {
                return NotFound();
            }

            var student = await _context.Students.FindAsync(user.PersonNumber);

            edition.RegisterInternship(student);
            await _context.SaveChangesAsync(token);

            return Ok();
        }
    }
}