"use server";

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

const BACK = "/dashboard/sponsors";

async function requireSponsorMutate() {
  const ctx = await requireOrgModule("sponsors");
  if (!canOrgMutate(ctx.role)) throw new Error("Your role is read-only.");
  return ctx;
}

async function sponsorFields(formData: FormData) {
  return {
    name: String(formData.get("name") || "").trim(),
    tier: String(formData.get("tier") || "PARTNER").trim().slice(0, 40) || "PARTNER",
    website: String(formData.get("website") || "").trim() || null,
    description: String(formData.get("description") || "").trim() || null,
    contactName: String(formData.get("contactName") || "").trim() || null,
    contactEmail: String(formData.get("contactEmail") || "").trim() || null,
    logoUrl: await saveUploadedImage(formData.get("logo"), "sponsors"), // null when no file chosen
  };
}

/** Add a sponsor/partner to the org's reusable partner book. */
export async function createOrgSponsor(formData: FormData) {
  const ctx = await requireSponsorMutate();
  let fields;
  try {
    fields = await sponsorFields(formData);
  } catch (e) {
    redirect(`${BACK}?error=${encodeURIComponent((e as Error).message)}`);
  }
  if (!fields!.name) redirect(`${BACK}?error=Sponsor name is required`);
  await db.sponsor.create({ data: { orgId: ctx.org.id, ...fields! } });
  await audit({ userId: ctx.user.id, action: "sponsor.pool.create", entity: "Sponsor", meta: { name: fields!.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${fields!.name} added to your partner book`)}`);
}

/** Edit a pool sponsor's profile (conference copies are edited inside each conference). */
export async function updateOrgSponsor(sponsorId: string, formData: FormData) {
  const ctx = await requireSponsorMutate();
  const sponsor = await db.sponsor.findUnique({ where: { id: sponsorId } });
  if (!sponsor || sponsor.orgId !== ctx.org.id || sponsor.conferenceId) throw new Error("Sponsor not found in your partner book.");
  let fields;
  try {
    fields = await sponsorFields(formData);
  } catch (e) {
    redirect(`${BACK}?error=${encodeURIComponent((e as Error).message)}`);
  }
  const { logoUrl, ...rest } = fields!;
  await db.sponsor.update({
    where: { id: sponsorId },
    data: { ...rest, name: rest.name || undefined, ...(logoUrl ? { logoUrl } : {}) },
  });
  await audit({ userId: ctx.user.id, action: "sponsor.pool.update", entity: "Sponsor", entityId: sponsorId });
  redirect(`${BACK}?saved=${encodeURIComponent("Sponsor updated")}`);
}

/** Remove a sponsor from the partner book (conference copies stay). */
export async function deleteOrgSponsor(sponsorId: string, _formData: FormData) {
  const ctx = await requireSponsorMutate();
  const sponsor = await db.sponsor.findUnique({ where: { id: sponsorId } });
  if (sponsor && sponsor.orgId === ctx.org.id && !sponsor.conferenceId) {
    await db.sponsor.delete({ where: { id: sponsorId } });
    await audit({ userId: ctx.user.id, action: "sponsor.pool.delete", entity: "Sponsor", entityId: sponsorId, meta: { name: sponsor.name } });
  }
  revalidatePath(BACK);
}

/** Attach a sponsor to a conference — copies the profile, the book entry stays reusable. */
export async function reuseSponsorAction(sponsorId: string, formData: FormData) {
  const ctx = await requireSponsorMutate();
  const targetId = String(formData.get("targetConferenceId") ?? "");
  const [sponsor, target] = await Promise.all([
    db.sponsor.findUnique({ where: { id: sponsorId }, include: { conference: { select: { orgId: true } } } }),
    db.conference.findUnique({ where: { id: targetId }, select: { id: true, orgId: true } }),
  ]);
  const ownerOrgId = sponsor?.conference?.orgId ?? sponsor?.orgId;
  if (!sponsor || ownerOrgId !== ctx.org.id) throw new Error("Sponsor not found in this organization.");
  if (!target || target.orgId !== ctx.org.id) redirect(`${BACK}?error=Pick a conference`);

  const dupe = await db.sponsor.findFirst({ where: { conferenceId: target.id, name: sponsor.name } });
  if (dupe) redirect(`${BACK}?error=${encodeURIComponent(`${sponsor.name} already sponsors that conference.`)}`);

  await db.sponsor.create({
    data: {
      conferenceId: target.id,
      name: sponsor.name,
      tier: sponsor.tier,
      logoUrl: sponsor.logoUrl,
      website: sponsor.website,
      description: sponsor.description,
      amount: 0, // sponsorship value is negotiated per conference
      contactName: sponsor.contactName,
      contactEmail: sponsor.contactEmail,
    },
  });
  await audit({ userId: ctx.user.id, conferenceId: target.id, action: "sponsor.reuse", entity: "Sponsor", meta: { name: sponsor.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${sponsor.name} added`)}`);
}
