using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using Microsoft.AspNetCore.Authorization; using PlotLine.Services; using PlotLine.ViewModels; namespace PlotLine.Controllers; [Authorize] public sealed class PlotThreadsController(IPlotService plots) : Controller { public async Task Index(int projectId) { var model = await plots.GetPlotThreadsAsync(projectId); return model is null ? NotFound() : View(model); } public async Task Create(int projectId, int? plotLineId) { var model = await plots.GetCreatePlotThreadAsync(projectId, plotLineId); return model is null ? NotFound() : View("Edit", model); } public async Task Edit(int id) { var model = await plots.GetEditPlotThreadAsync(id); return model is null ? NotFound() : View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task Save(PlotThreadEditViewModel model) { if (ModelState.IsValid) { try { await plots.SavePlotThreadAsync(model); return RedirectToAction("Manage", "PlotLineWorkspace", new { projectId = model.ProjectID }); } catch (SqlException exception) when (exception.Number == 51101) { ModelState.AddModelError(string.Empty, exception.Message); } catch (ArgumentException exception) { ModelState.AddModelError(string.Empty, exception.Message); } } var form = await plots.PopulatePlotThreadFormAsync(model); return form is null ? NotFound() : View("Edit", form); } [HttpPost] [ValidateAntiForgeryToken] public async Task Archive(int id, int projectId) { try { await plots.ArchivePlotThreadAsync(id); } catch (SqlException exception) when (exception.Number == 51101) { TempData["ThreadPlanningConflict"] = exception.Message; return RedirectToAction(nameof(Edit), new { id }); } TempData["ArchiveMessage"] = "Plot thread archived. You can restore it from Archived Items."; return RedirectToAction(nameof(Index), new { projectId }); } }