"use server"; import { db } from "@/db"; import { forms } from "@/db/schema"; import { eq } from "drizzle-orm"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { getServerSession } from "next-auth"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; function requireAdmin() { // No async check needed here — callers should check session before sensitive ops } export async function createForm(formData: FormData) { const session = await getServerSession(authOptions); const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean); const discordId = (session?.user as { discordId?: string } | undefined)?.discordId; if (!discordId || !adminIds.includes(discordId)) { throw new Error("Unauthorized"); } const title = formData.get("title") as string; const description = formData.get("description") as string | null; const [form] = await db .insert(forms) .values({ title, description: description ?? null }) .returning(); revalidatePath("/form/admin"); redirect(`/form/admin/${form.id}/edit`); } export async function updateForm(id: string, data: { title: string; description?: string; isOpen?: boolean }) { const session = await getServerSession(authOptions); const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean); const discordId = (session?.user as { discordId?: string } | undefined)?.discordId; if (!discordId || !adminIds.includes(discordId)) { throw new Error("Unauthorized"); } await db.update(forms).set(data).where(eq(forms.id, id)); revalidatePath("/form"); revalidatePath("/form/admin"); } export async function deleteForm(id: string) { const session = await getServerSession(authOptions); const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean); const discordId = (session?.user as { discordId?: string } | undefined)?.discordId; if (!discordId || !adminIds.includes(discordId)) { throw new Error("Unauthorized"); } await db.delete(forms).where(eq(forms.id, id)); revalidatePath("/form/admin"); redirect("/form/admin"); }