using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Services.Investigations; namespace PlotLine.Controllers; [Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class InvestigationCompanionController(InvestigationAccess gate,IInvestigationGuidanceRepository repository,InvestigationGuidanceService service,IInvestigationRepository investigations):Controller { IActionResult Error(int status,string message){ if((ControllerContext.ActionDescriptor.ActionName==nameof(Open)||ControllerContext.ActionDescriptor.ActionName==nameof(Update)&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")){ Response.StatusCode=status;ViewData["Failure"]=message; if(int.TryParse(Request.Form["bookId"],out var book))ViewData["BookID"]=book; if(Guid.TryParse(Request.Form["id"],out var id))ViewData["InvestigationID"]=id; return View("~/Views/InvestigationCompanion/Failure.cshtml"); } return StatusCode(status,new{message}); } int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); async Task Guard(Func> run){if(!gate.Enabled)return NotFound();Response.Headers["X-Robots-Tag"]="noindex, nofollow, noarchive";try{return await run();}catch(Exception e)when(e is UnauthorizedAccessException or KeyNotFoundException){return NotFound();}catch(ArgumentException e){return Error(400,e.Message);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){return NotFound();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){return Error(409,"Guidance changed in another window. Refresh before trying again.");}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or TimeoutException){return Error(503,"Guidance is temporarily unavailable. Your saved investigation is retained.");}} async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Verify(GuidanceRecord r){var(i,_,_)=InvestigationGuidanceService.Decode(r);if(i.UserID!=Author||i.BookID!=r.BookID||i.ProjectID!=r.ProjectID)throw new UnauthorizedAccessException();var c=await service.Catalogue(i.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)throw new UnauthorizedAccessException();return(r,c);} async Task<(GuidanceRecord,PlotLine.Models.Investigations.Catalogue)> Load(int? project,int? book,Guid? id)=>await Verify(await repository.Read(Author,project,book,id)??throw new KeyNotFoundException()); [HttpGet("/InvestigationCompanion/Summary")] public Task Summary(int? projectId,int? bookId)=>Guard(async()=>{ if(projectId is not >0&&bookId is not >0)return Json(new{active=false}); var r=await repository.Read(Author,projectId,bookId);if(r==null)return Json(new{active=false}); var(verified,c)=await Verify(r); // same ownership guard as explicit IDs return Json(new{active=true,hasSnapshot=verified.EvaluationJson!=null,summary=service.Summary(verified,c),resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId=r.BookID,id=r.ID})}); }); [HttpGet("/InvestigationCompanion/Saved")] public Task Saved(int bookId)=>Guard(async()=>{ var rows=await repository.List(Author,bookId);var result=new List(); foreach(var row in rows){var c=await service.Catalogue(row.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)continue; result.Add(new{row.ID,row.BookID,row.GuidanceVersion,updatedUtc=DateTime.SpecifyKind(row.UpdatedUtc,DateTimeKind.Utc),status=row.Finished?"Journey finished":row.IsActive?"Active guidance ยท "+row.Status:row.Status,hasResults=row.Status=="Results available",concern=c.Concerns.SingleOrDefault(x=>x.Id==row.Concern)?.Text??"Saved investigation",resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId,id=row.ID}),continueUrl=Url.Action("Update",new{bookId,id=row.ID})});} return Json(result); }); [HttpGet("/InvestigationCompanion/Evidence")] public Task Evidence(int bookId,Guid id,string finding)=>Guard(async()=>{ var(r,c)=await Load(null,bookId,id);var(i,_,s)=InvestigationGuidanceService.Decode(r);service.Select(r,c,s,finding,null); var full=await investigations.Read(Author,bookId,id)??throw new KeyNotFoundException(); return Json(full.Answers.Where(a=>c.Questions.Any(q=>q.Id==a.Question&&q.Options.Any(o=>o.Id==a.Option&&o.Contributions.Any(v=>v.Hypothesis==finding&&v.Weight>0)))).Take(5).Select(a=>{var q=c.Questions.Single(q=>q.Id==a.Question);return new{question=q.Text,answer=q.Options.Single(o=>o.Id==a.Option).Text,explanation=a.Explanation};})); }); [HttpPost("/InvestigationCompanion/Update"),ValidateAntiForgeryToken] public Task Update(int bookId,Guid id,int version,string operation,string? finding,string? capability,string? progress)=>Guard(async()=>{ var(r,c)=await Load(null,bookId,id);if(r.GuidanceVersion!=version)return Error(409,"Guidance changed in another window. Refresh before trying again.");var(_,_,s)=InvestigationGuidanceService.Decode(r); if(operation is "select" or "progress"){ if(!r.IsActive)throw new ArgumentException("Activate this investigation first.");service.Select(r,c,s,finding??"",capability); if(operation=="progress"){if(capability==null||!InvestigationGuidanceService.ProgressStates.Contains(progress))throw new ArgumentException("Choose a progress state.");s.Progress[InvestigationGuidanceService.Key(finding!,capability)]=progress!;} }else if(operation is not("activate" or "dismiss" or "finish"))throw new ArgumentException("Unknown guidance action."); await service.Save(Author,r,s,operation is "select" or "progress"?"save":operation); if(operation=="activate"&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")return RedirectToAction("Explore","Writer",new{bookId,investigation=id}); return Json(new{ok=true}); }); [HttpPost("/InvestigationCompanion/Open"),ValidateAntiForgeryToken] public Task Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var timer=System.Diagnostics.Stopwatch.StartNew();var(r,c)=await Load(null,bookId,id);Response.Headers.Append("Server-Timing",FormattableString.Invariant($"guidance-load;dur={timer.Elapsed.TotalMilliseconds:F2}"));var target=await service.Open(Author,r,c,finding,capability,(name,ms)=>Response.Headers.Append("Server-Timing",FormattableString.Invariant($"{name};dur={ms:F2}")));return RedirectToAction(target.Action,target.Controller,target.Values);}); }