using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class SpatialContextController(ContextSpatial spatial,MapRepository maps,ICurrentUserService user):Controller { private async Task Guard(Func> action) { try{return await action();}catch(UnauthorizedAccessException){return Forbid();} catch(SqlException e)when(e.Number is 51010 or 51011 or 51012){return StatusCode(e.Number==51010?403:409,new{message=e.Message});} catch(ArgumentException e){return BadRequest(new{message=e.Message});} } [HttpGet] public Task State(int bookId,int sceneId,int? locationId)=>Guard(async()=>Json(await spatial.Read(bookId,sceneId,locationId))); [HttpPost,ValidateAntiForgeryToken] public Task Mutate([FromBody] SpatialMutation input)=>Guard(async()=>ModelState.IsValid&&input!=null?Json(await spatial.Mutate(input)):BadRequest(new{message="Check the spatial operation."})); public sealed record UndoInput(string Token); [HttpPost,ValidateAntiForgeryToken] public Task Undo([FromBody] UndoInput input)=>Guard(async()=>input!=null&&!string.IsNullOrWhiteSpace(input.Token)&&input.Token.Length<=16000?Json(await spatial.Undo(input.Token)):BadRequest(new{message="Undo is unavailable."})); [HttpPost,ValidateAntiForgeryToken] public Task Create([FromBody] SpatialCreation input)=>Guard(async()=>ModelState.IsValid&&input!=null?Json(await spatial.Create(input)):BadRequest(new{message="Check the location details."})); [HttpGet] public Task Map(int bookId,int sceneId,int id)=>Guard(async()=>{ var scope=await spatial.Scope(bookId,sceneId);var document=await maps.GetAsync(scope.ProjectID,id,user.UserId!.Value);if(document==null)return NotFound(); ViewData["SpatialRenderer"]=true;ViewData["DetachedWorkspace"]=true; return View("~/Views/Maps/Index.cshtml",new MapsViewModel{Project=new(){ProjectID=scope.ProjectID},Maps=[document.Map],Document=document}); }); [HttpGet] public Task Floor(int bookId,int sceneId,int id)=>Guard(async()=>PartialView("~/Views/Writing/_SpatialFloorCanvas.cshtml",await spatial.Floor(bookId,sceneId,id))); }