using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using System.Text.Json; using PlotLine.Data; using PlotLine.Services; namespace PlotLine.Controllers; [Authorize,Route("Writing/Intent/Assessment")] public sealed class IntentAssessmentController(IntentAssessmentService service,IIntentAssessmentRepository repository):Controller { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet]public async Task Read(int sceneId){try{return PartialView("~/Views/Writing/_IntentAssessment.cshtml",await service.Read(Author,sceneId));}catch(UnauthorizedAccessException){return Forbid();}} [HttpPost,ValidateAntiForgeryToken]public async Task Analyse(int sceneId,Guid? requestID,int? expectedCredits){try{return PartialView("~/Views/Writing/_IntentAssessment.cshtml",await service.Analyse(Author,sceneId,HttpContext.RequestAborted,requestID,expectedCredits));}catch(UnauthorizedAccessException){return Forbid();}catch(OperationCanceledException){return StatusCode(408,"Assessment stopped or timed out. Previous saved evidence is preserved.");}catch(Exception e)when(e is ArgumentException or JsonException or HttpRequestException or InvalidOperationException){return BadRequest("Assessment could not finish. Check the saved manuscript and plan, then retry. Previous evidence and author decisions are preserved.");}} [HttpPost("decision"),ValidateAntiForgeryToken]public async Task Decide(int sceneId,string hash,string key,string decision){try{var frame=await service.Read(Author,sceneId);if(frame.Hash!=hash||frame.Saved?.InputHash!=hash)return Conflict("Saved prose or intentions changed. Reassess before deciding.");if(!frame.Saved.Evidence.Any(x=>x.Key==key)||decision is not ("acknowledged" or "dismissed" or "deferred" or "pending"))return BadRequest();await repository.Decide(Author,sceneId,hash,key,decision);return PartialView("~/Views/Writing/_IntentAssessment.cshtml",await service.Read(Author,sceneId));}catch(UnauthorizedAccessException){return Forbid();}} }