using System.ComponentModel.DataAnnotations; using System.Text.Json; using maintenance.Data; using maintenance.Data.Entities; using maintenance.Services.Pages; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace maintenance.Pages.Admin.Templates; [Authorize(Policy = "AdminOnly")] public sealed class CreateModel : PageModel { private readonly AppDbContext _dbContext; public CreateModel(AppDbContext dbContext) { _dbContext = dbContext; } [BindProperty] public InputModel Input { get; set; } = new(); public List SourceTemplates { get; private set; } = []; public sealed class InputModel { [Required] public Guid SourceTemplateId { get; set; } [Required] [StringLength(100, MinimumLength = 3)] [RegularExpression("^[a-z0-9-]+$")] [Display(Name = "Page Key")] public string NewKey { get; set; } = string.Empty; [Required] [StringLength(200)] [Display(Name = "Display Name")] public string DisplayName { get; set; } = string.Empty; [StringLength(100)] [RegularExpression("^[a-z0-9-]*$")] [Display(Name = "Stub (optional)")] public string? Stub { get; set; } } public async Task OnGetAsync() { await LoadSourcesAsync(); } public async Task OnPostAsync() { await LoadSourcesAsync(); if (!ModelState.IsValid) { return Page(); } var source = await _dbContext.ManagedPages .AsNoTracking() .FirstOrDefaultAsync(t => t.Id == Input.SourceTemplateId, HttpContext.RequestAborted); if (source is null) { ModelState.AddModelError(nameof(Input.SourceTemplateId), "Source page was not found."); return Page(); } var normalizedKey = Input.NewKey.Trim().ToLowerInvariant(); var normalizedStub = NormalizeStub(Input.Stub); var exists = await _dbContext.ManagedPages .AnyAsync(t => t.Key == normalizedKey, HttpContext.RequestAborted); if (exists) { ModelState.AddModelError(nameof(Input.NewKey), "A page with this key already exists."); return Page(); } if (!string.IsNullOrWhiteSpace(normalizedStub)) { var stubExists = await _dbContext.ManagedPages .AnyAsync(t => t.PageKind == source.PageKind && t.NormalizedStub == normalizedStub, HttpContext.RequestAborted); if (stubExists) { ModelState.AddModelError(nameof(Input.Stub), "A page with this stub already exists for this page kind."); return Page(); } } var clone = new ManagedPageEntity { Id = Guid.NewGuid(), Key = normalizedKey, Stub = normalizedStub, NormalizedStub = normalizedStub, DisplayName = Input.DisplayName.Trim(), PageKind = source.PageKind, IsDefaultFallback = false, IsEnabled = false, OverrideWindow = false, Priority = source.Priority, StartUtc = source.StartUtc, EndUtc = source.EndUtc, RecurrenceRule = source.RecurrenceRule, ContentJson = CloneJson(source.ContentJson), LastUpdatedBy = User.Identity?.Name ?? "unknown", LastUpdatedAtUtc = DateTime.UtcNow }; _dbContext.ManagedPages.Add(clone); await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); return RedirectToPage("./Edit", new { id = clone.Id }); } private async Task LoadSourcesAsync() { SourceTemplates = await _dbContext.ManagedPages .AsNoTracking() .OrderBy(t => t.PageKind) .ThenBy(t => t.Key) .Select(t => new SelectListItem { Value = t.Id.ToString(), Text = $"{t.PageKind} - {t.Key}" }) .ToListAsync(HttpContext.RequestAborted); } private static string CloneJson(string json) { try { var model = JsonSerializer.Deserialize(json) ?? new PageContentModel(); return JsonSerializer.Serialize(model); } catch { return JsonSerializer.Serialize(new PageContentModel()); } } private static string? NormalizeStub(string? stub) { if (string.IsNullOrWhiteSpace(stub)) { return null; } return stub.Trim().ToLowerInvariant(); } }