"use server"; import { revalidatePath } from "next/cache"; import { contentMutationService, createContentMutationInvocation, } from "@/features/housekeeping/domains/content/services/mutations"; import { createCorrelationId } from "@/features/housekeeping/foundation/contracts"; import { requirePermission } from "@/lib/admin/guard"; import { PERMS } from "@/lib/permissions"; function templateInput(formData: FormData) { return { name: String(formData.get("name") ?? "") .normalize("NFC") .trim() .slice(0, 255), subject: String(formData.get("subject") ?? "") .normalize("NFC") .trim() .slice(0, 255), body: String(formData.get("body") ?? "").normalize("NFC"), variables: String(formData.get("variables") ?? "") .normalize("NFC") .trim(), isActive: formData.get("isActive") != null, }; } export async function createEmailTemplate(formData: FormData): Promise { const staff = await requirePermission(PERMS.PAGES_EDIT); const input = templateInput(formData); if (!input.name || !input.subject || !input.body) return; const result = await contentMutationService.execute( createContentMutationInvocation(staff, createCorrelationId()), "email-template.change", { action: "create", ...input }, ); if (!result.ok) throw new Error("Email template creation failed"); revalidatePath("/admin/email-templates"); } export async function updateEmailTemplate(formData: FormData): Promise { const staff = await requirePermission(PERMS.PAGES_EDIT); const id = String(formData.get("id") ?? "").normalize("NFC"); if (!/^\d+$/u.test(id)) return; const input = templateInput(formData); if (!input.subject || !input.body) return; const result = await contentMutationService.execute( createContentMutationInvocation(staff, createCorrelationId()), "email-template.change", { action: "update", id, ...input }, ); if (!result.ok) throw new Error("Email template update failed"); revalidatePath("/admin/email-templates"); } export async function deleteEmailTemplate(formData: FormData): Promise { const staff = await requirePermission(PERMS.PAGES_EDIT); const id = String(formData.get("id") ?? "") .normalize("NFC") .trim(); if (!/^[1-9]\d*$/u.test(id)) return; const result = await contentMutationService.execute( createContentMutationInvocation(staff, createCorrelationId()), "email-template.change", { action: "delete", id }, ); if (!result.ok) throw new Error("Email template deletion failed"); revalidatePath("/admin/email-templates"); }