"use server";

import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { requireOrgModule, canOrgMutate } from "@/lib/org";
import { audit } from "@/lib/audit";

async function requireConfInOrg(confId: string) {
  const ctx = await requireOrgModule("conferences");
  if (!canOrgMutate(ctx.role)) throw new Error("Your role is read-only.");
  const conf = await db.conference.findUnique({ where: { id: confId } });
  if (!conf || conf.orgId !== ctx.org.id) throw new Error("Conference not found in this organization.");
  return { ctx, conf };
}

export async function orgSetConferenceStatus(confId: string, status: string, _formData: FormData) {
  const { ctx } = await requireConfInOrg(confId);
  await db.conference.update({ where: { id: confId }, data: { status } });
  await audit({ userId: ctx.user.id, conferenceId: confId, action: `conference.status.${status.toLowerCase()}`, entity: "Conference", entityId: confId });
  revalidatePath("/dashboard/conferences");
}

/** Delete a conference — only OWNER/ADMIN, and only DRAFT or ARCHIVED (same guard as the platform admin). */
export async function orgDeleteConference(confId: string, _formData: FormData) {
  const { ctx, conf } = await requireConfInOrg(confId);
  if (!["OWNER", "ADMIN"].includes(ctx.role)) throw new Error("Only organization owners/admins can delete conferences.");
  if (!["DRAFT", "ARCHIVED"].includes(conf.status)) throw new Error("Archive the conference before deleting it.");
  await db.conference.delete({ where: { id: confId } });
  await audit({ userId: ctx.user.id, action: "conference.delete", entity: "Conference", entityId: confId, meta: { name: conf.name } });
  revalidatePath("/dashboard/conferences");
}
