using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Services.Context; namespace PlotLine.Controllers; [Authorize, ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] public sealed class ContextThreadsController(ContextThreads threads) : 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) => Guard(async () => ModelState.IsValid && bookId > 0 && sceneId > 0 ? Json(await threads.Read(bookId, sceneId)) : BadRequest()); [HttpPost, ValidateAntiForgeryToken] public Task Add([FromBody] ContextThreadSelection input) => Guard(async () => { if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0) return BadRequest(); await threads.Add(input); return Json(new { saved = true }); }); [HttpPost, ValidateAntiForgeryToken] public Task Remove([FromBody] ContextThreadRemoval input) => Guard(async () => { if (!ModelState.IsValid || input == null || input.BookID <= 0 || input.SceneID <= 0 || input.ThreadID <= 0) return BadRequest(); await threads.Remove(input); return Json(new { saved = true }); }); }