using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public sealed class ContextToolsController(ContextCharacterEditing editing):Controller { [HttpGet("EditCharacter")] public async Task EditCharacter(int bookId,int sceneId,int characterId,string field) {try{return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",await editing.Read(bookId,sceneId,characterId,field));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();}} [HttpPost("EditCharacter"),ValidateAntiForgeryToken] public async Task SaveCharacter(ContextCharacterEditForm model) { try{ if(ModelState.IsValid){await editing.Save(model);return Ok(new{saved=true,bookId=model.BookID});} return await Invalid(model,"Check the correction below."); }catch(UnauthorizedAccessException){return Forbid();} catch(Exception e)when(e is ArgumentException or InvalidOperationException){return await Invalid(model,e.Message);} catch(Microsoft.Data.SqlClient.SqlException){return await Invalid(model,"The correction could not be saved. Your draft is retained; retry when the connection recovers.");} } private async Task Invalid(ContextCharacterEditForm input,string error) { ContextCharacterEditForm frame; try{frame=await editing.Read(input.BookID,input.SceneID,input.CharacterID,input.Field);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();} frame.Value=input.Value;frame.Fingerprint=input.Fingerprint;ModelState.AddModelError(nameof(input.Value),error);Response.StatusCode=422; return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",frame); } }