using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Models; using PlotLine.Services.Writer; namespace PlotLine.Controllers; [Authorize] public sealed class WriterAuthoringController(IWriterAuthoringService authoring):Controller { private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet] public async Task Inspect(int bookId,int chapterId,int? sceneId){Response.Headers.CacheControl="no-store";try{return PartialView("~/Views/Writer/_WriterAuthoring.cshtml",await authoring.Read(Actor,bookId,chapterId,sceneId));}catch(SqlException e)when(e.Number==51000){return NotFound();}catch(KeyNotFoundException){return NotFound();}} [HttpPost,ValidateAntiForgeryToken] public async Task Save(int bookId,int chapterId,int? sceneId,string kind,int entityId,string version){ var values=AuthoringSchema.Fields(kind).ToDictionary(f=>f.Name,f=>(string?)Request.Form[f.Name].ToString()); try{await authoring.Save(Actor,bookId,chapterId,sceneId,kind,entityId,version,values);return Json(new{success=true});} catch(AuthoringConflictException e){return Conflict(new{message=e.Message});} catch(KeyNotFoundException){return NotFound();} catch(ArgumentException e){return BadRequest(new{message=e.Message});} catch(SqlException e)when(e.Number is 51000 or 51002 or 51003){return StatusCode(e.Number==51000?404:e.Number==51002?409:400,new{message=e.Message});} } }