"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, fetchAndStoreImage } from "@/lib/storage";
import { fetchLinkedInProfile, normalizeLinkedInUrl } from "@/lib/linkedin";
import { audit } from "@/lib/audit";

const BACK = "/dashboard/speakers";

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

function socialLinksFrom(formData: FormData): string | null {
  const links = {
    linkedin: String(formData.get("linkedin") || "").trim(),
    twitter: String(formData.get("twitter") || "").trim(),
    website: String(formData.get("website") || "").trim(),
  };
  return Object.values(links).some(Boolean) ? JSON.stringify(links) : null;
}

async function speakerFields(formData: FormData) {
  return {
    name: String(formData.get("name") || "").trim(),
    email: String(formData.get("email") || "").trim() || null,
    organization: String(formData.get("organization") || "").trim() || null,
    designation: String(formData.get("designation") || "").trim() || null,
    bio: String(formData.get("bio") || "").trim() || null,
    speakerType: String(formData.get("speakerType") || "SPEAKER"),
    socialLinks: socialLinksFrom(formData),
    photoUrl: await saveUploadedImage(formData.get("photo")), // null when no file chosen
  };
}

/** Add a speaker to the org's reusable pool — no conference needed yet. */
export async function createOrgSpeaker(formData: FormData) {
  const ctx = await requireSpeakerMutate();
  let fields;
  try {
    fields = await speakerFields(formData);
  } catch (e) {
    redirect(`${BACK}?error=${encodeURIComponent((e as Error).message)}`);
  }
  if (!fields!.name) redirect(`${BACK}?error=Speaker name is required`);
  await db.speaker.create({ data: { orgId: ctx.org.id, ...fields! } });
  await audit({ userId: ctx.user.id, action: "speaker.pool.create", entity: "Speaker", meta: { name: fields!.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${fields!.name} added to your speaker database`)}`);
}

/** Add a pool speaker straight from a LinkedIn profile URL. */
export async function importOrgSpeakerFromLinkedIn(formData: FormData) {
  const ctx = await requireSpeakerMutate();
  const url = normalizeLinkedInUrl(String(formData.get("linkedinUrl") || ""));
  if (!url) redirect(`${BACK}?error=${encodeURIComponent("That doesn't look like a LinkedIn profile URL (expected linkedin.com/in/…).")}`);
  const profile = await fetchLinkedInProfile(url!);
  if (!profile.name) redirect(`${BACK}?error=${encodeURIComponent("Couldn't derive a name from that profile URL.")}`);
  const photoUrl = profile.photoUrl ? await fetchAndStoreImage(profile.photoUrl) : null;
  const speaker = await db.speaker.create({
    data: {
      orgId: ctx.org.id,
      name: profile.name!,
      designation: profile.designation ?? null,
      organization: profile.organization ?? null,
      bio: profile.bio ?? null,
      photoUrl,
      socialLinks: JSON.stringify({ linkedin: url }),
    },
  });
  await audit({ userId: ctx.user.id, action: "speaker.pool.import.linkedin", entity: "Speaker", entityId: speaker.id, meta: { url } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${profile.name} imported from LinkedIn${profile.partial ? " (partial profile — review the details)" : ""}`)}`);
}

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

/** Remove a speaker from the pool (copies already placed in conferences stay). */
export async function deleteOrgSpeaker(speakerId: string, _formData: FormData) {
  const ctx = await requireSpeakerMutate();
  const speaker = await db.speaker.findUnique({ where: { id: speakerId } });
  if (speaker && speaker.orgId === ctx.org.id && !speaker.conferenceId) {
    await db.speaker.delete({ where: { id: speakerId } });
    await audit({ userId: ctx.user.id, action: "speaker.pool.delete", entity: "Speaker", entityId: speakerId, meta: { name: speaker.name } });
  }
  revalidatePath(BACK);
}

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

  const dupe = await db.speaker.findFirst({
    where: {
      conferenceId: target.id,
      OR: [{ name: speaker.name }, ...(speaker.email ? [{ email: speaker.email }] : [])],
    },
  });
  if (dupe) redirect(`${BACK}?error=${encodeURIComponent(`${speaker.name} is already added to that conference.`)}`);

  await db.speaker.create({
    data: {
      conferenceId: target.id,
      name: speaker.name,
      email: speaker.email,
      bio: speaker.bio,
      photoUrl: speaker.photoUrl,
      organization: speaker.organization,
      designation: speaker.designation,
      socialLinks: speaker.socialLinks,
      speakerType: speaker.speakerType,
    },
  });
  await audit({ userId: ctx.user.id, conferenceId: target.id, action: "speaker.reuse", entity: "Speaker", meta: { name: speaker.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${speaker.name} added`)}`);
}
