using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; namespace PlotLine.Controllers; [Authorize] public sealed class MapsController(MapRepository maps, IProjectRepository projects, ILocationRepository locations, IFloorPlanRepository floorPlans, IProjectAccessService access, ICurrentUserService currentUser) : Controller { private int UserID => currentUser.UserId!.Value; public async Task Index(int projectId, int? id) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); var project = await projects.GetForUserAsync(projectId, UserID); if (project is null) return NotFound(); var document = id.HasValue ? await maps.GetAsync(projectId, id.Value, UserID) : null; if (id.HasValue && document is null) return NotFound(); return View(new MapsViewModel { Project = project, Maps = await maps.ListAsync(projectId, UserID), Document = document, Locations = await locations.ListByProjectAsync(projectId), FloorPlans = await floorPlans.ListByProjectAsync(projectId) }); } [HttpGet] public async Task State(int projectId, int id) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); var document = await maps.GetAsync(projectId, id, UserID); return document is null ? NotFound() : Json(document); } [HttpPost, ValidateAntiForgeryToken] public async Task Create(StoryMap model) { if (!await access.CanAccessProjectAsync(model.ProjectID)) return NotFound(); if (!ModelState.IsValid || !MapValidation.Kinds.Contains(model.Kind)) return BadRequest("Choose a map name and kind."); try { return Json(new { id = await maps.CreateAsync(model, UserID) }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(8_000_000)] public async Task Save([FromBody] MapDocument document) { if (document is null || document.Map is null) return BadRequest(new { message = "Choose a map." }); if (!await access.CanAccessProjectAsync(document.Map.ProjectID)) return NotFound(); if (!ModelState.IsValid) return BadRequest(new { message = "Check map fields." }); var error = MapValidation.Validate(document); if (error is not null) return BadRequest(new { message = error }); try { await maps.SaveAsync(document, UserID); return Json(await maps.GetAsync(document.Map.ProjectID, document.Map.MapID, UserID)); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } [HttpPost, ValidateAntiForgeryToken] public async Task Delete(int projectId, int id, int revision) { if (!await access.CanAccessProjectAsync(projectId)) return NotFound(); try { await maps.DeleteAsync(projectId, id, revision, UserID); return Json(new { ok = true }); } catch (SqlException ex) when (ex.Number == 51000) { return Conflict(new { message = ex.Message }); } } }