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;
namespace InternshipSystem.Api.Controllers
{
    [ApiController]
    [Route("register")]
    public class RegistrationController : ControllerBase
    {
        private readonly InternshipDbContext _context;
        public RegistrationController(InternshipDbContext context)
        {
            _context = context;
        }
        
        /// 
        /// Register student for edition using provided registration code
        /// 
        /// GUID of edition 
        /// 
        /// If the student was successfully registered
        /// If the provided registration code was malformed
        /// The registration code doesn't match any open edition
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [Authorize]
        public async Task RegisterStudentForEdition([FromBody] Guid registrationCode, CancellationToken token)
        {
            var edition = await _context.Editions.FindAsync(registrationCode, token);
            if (edition == null)
            {
                return NotFound();
            }
            
            var personNumber = long.Parse(User.FindFirst(InternshipClaims.PersonNumber).Value);
            
            var student = await _context.Students.FindAsync(personNumber, token);
            edition.RegisterInternship(student);
            await _context.SaveChangesAsync(token);
            
            return Ok();
        }
        
    }
}