using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using QuestionsApi.Models; using QuestionsApi.Services; using System.Security.Claims; namespace QuestionsApi.Controllers; [ApiController] [Route("api/study-sessions")] [Authorize(Roles = "USER,SUPER")] public sealed class StudySessionsController(StudySessionStore sessions) : ControllerBase { [HttpPost] public async Task Create(CreateStudySessionRequest request) { try { return Ok(sessions.Envelope(await sessions.CreateAsync(UserId(), request))); } catch (ArgumentException exception) { return BadRequest(exception.Message); } catch (InvalidOperationException exception) { return Conflict(exception.Message); } } [HttpGet("active")] public async Task Active() { var session = await sessions.GetActiveAsync(UserId()); return session is null ? NoContent() : Ok(sessions.Envelope(session)); } [HttpPost("{id}/finish")] public async Task Finish(string id) { var result = await sessions.FinishEarlyAsync(id, UserId()); return result is null ? NotFound() : Ok(result); } [HttpGet("{id}/summary")] public async Task Summary(string id) { var session = await sessions.GetOwnedAsync(id, UserId()); return session is null ? NotFound() : Ok(sessions.Envelope(session)); } [HttpPost("{id}/check")] public async Task Check(string id) { var result = await sessions.CheckAsync(id, UserId()); return result is null ? NotFound() : Ok(result); } private string UserId() => User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue(ClaimTypes.Name) ?? User.Identity?.Name ?? throw new UnauthorizedAccessException(); }