"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { randomBytes, randomInt } from "crypto";
import { z } from "zod";
import { db } from "@/lib/db";
import { createSession, getCurrentUser, hashPassword, isOrganizer } from "@/lib/auth";
import { sendOnboardingCodeEmail, sendOnboardingWelcomeEmail, sendWelcomeEmail } from "@/lib/email";
import { parseJSON } from "@/lib/utils";
import { audit } from "@/lib/audit";
import { createConferenceForUser, ensureOwnOrg, DRAFT_COOKIE } from "@/lib/onboarding";

const CODE_TTL_MIN = 15;
const MAX_ATTEMPTS = 5;

const basicsSchema = z.object({
  name: z.string().min(3, "Conference name is too short"),
  type: z.enum(["PHYSICAL", "VIRTUAL", "HYBRID"]),
  category: z.string().default("TECH"),
  startAt: z.string().min(1, "Start date required"),
  endAt: z.string().min(1, "End date required"),
  tagline: z.string().optional(),
  description: z.string().optional(),
  venueName: z.string().optional(),
  city: z.string().optional(),
  state: z.string().optional(),
  district: z.string().optional(),
  capacity: z.string().optional(),
  primaryColor: z.string().default("#4f46e5"),
});

type Basics = z.infer<typeof basicsSchema>;

async function getDraft() {
  const jar = await cookies();
  const token = jar.get(DRAFT_COOKIE)?.value;
  if (!token) return null;
  const draft = await db.onboardingDraft.findUnique({ where: { token } });
  return draft && draft.status !== "COMPLETED" ? draft : null;
}

/** Step 1 — public conference basics. Logged-in users skip verification entirely. */
export async function startConferenceAction(formData: FormData) {
  const parsed = basicsSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) {
    redirect(`/start?error=${encodeURIComponent(parsed.error.issues[0].message)}`);
  }
  const d = parsed.data;
  const startAt = new Date(d.startAt);
  const endAt = new Date(d.endAt);
  if (isNaN(startAt.getTime()) || isNaN(endAt.getTime()) || endAt < startAt) {
    redirect(`/start?error=${encodeURIComponent("End date must be after the start date.")}`);
  }

  // Already signed in? Create immediately — no verification needed.
  const user = await getCurrentUser();
  if (user) {
    if (!isOrganizer(user)) {
      await db.user.update({ where: { id: user.id }, data: { platformRole: "ORGANIZER" } });
    }
    const orgId = await ensureOwnOrg(user);
    const conf = await createConferenceForUser(user.id, orgId, d);
    await audit({ userId: user.id, conferenceId: conf.id, action: "conference.create", entity: "Conference", entityId: conf.id, meta: { via: "start-funnel" } });
    redirect(`/dashboard/c/${conf.id}?welcome=1`);
  }

  // Anonymous: park the basics in a draft and move to email verification.
  const token = randomBytes(24).toString("hex");
  await db.onboardingDraft.create({ data: { token, data: JSON.stringify(d) } });
  const jar = await cookies();
  jar.set(DRAFT_COOKIE, token, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 });
  redirect("/start/verify");
}

/** Step 2 — collect email (and name/org), send the 6-digit code. */
export async function sendOnboardingCodeAction(formData: FormData) {
  const draft = await getDraft();
  if (!draft) redirect("/start?error=Your session expired — fill the form again (takes a minute).");

  const email = String(formData.get("email") ?? "").trim().toLowerCase();
  const name = String(formData.get("name") ?? "").trim();
  const orgName = String(formData.get("orgName") ?? "").trim();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) redirect("/start/verify?error=Enter a valid email address&edit=1");
  if (!name) redirect("/start/verify?error=Your name is required&edit=1");

  const code = String(randomInt(100000, 1000000));
  await db.onboardingDraft.update({
    where: { id: draft!.id },
    data: { email, name, orgName: orgName || null, code, codeExpiresAt: new Date(Date.now() + CODE_TTL_MIN * 60_000), attempts: 0, status: "CODE_SENT" },
  });

  const basics = parseJSON<Basics>(draft!.data, {} as Basics);
  const result = await sendOnboardingCodeEmail({
    email, name, code,
    conferenceName: basics.name ?? "your conference",
    expiresMinutes: CODE_TTL_MIN,
  });

  // When email isn't configured (local/dev), surface the code so the flow stays testable.
  const devHint = result !== "SENT" && process.env.NODE_ENV !== "production" ? `&dev=${code}` : "";
  redirect(`/start/verify?sent=1${devHint}`);
}

/** Step 3 — verify the code: create account + org + conference, auto-login, land in the workspace. */
export async function verifyOnboardingCodeAction(formData: FormData) {
  const draft = await getDraft();
  if (!draft || !draft.email || !draft.code) redirect("/start?error=Your session expired — fill the form again.");

  if (draft!.attempts >= MAX_ATTEMPTS) {
    redirect("/start/verify?error=Too many attempts — resend a fresh code.&sent=1");
  }
  const code = String(formData.get("code") ?? "").replace(/\D/g, "");
  if (!draft!.codeExpiresAt || draft!.codeExpiresAt < new Date()) {
    redirect("/start/verify?error=That code expired — resend a fresh one.&sent=1");
  }
  if (code !== draft!.code) {
    await db.onboardingDraft.update({ where: { id: draft!.id }, data: { attempts: { increment: 1 } } });
    redirect("/start/verify?error=That code doesn't match — check the email and try again.&sent=1");
  }

  const basics = basicsSchema.parse(parseJSON(draft!.data, {}));

  // Find or create the account — OTP ownership of the inbox is the proof.
  let user = await db.user.findUnique({ where: { email: draft!.email! } });
  let tempPassword: string | null = null;
  if (!user) {
    tempPassword = `cfx-${randomBytes(4).toString("hex")}`;
    user = await db.user.create({
      data: {
        email: draft!.email!,
        name: draft!.name ?? "Organizer",
        organization: draft!.orgName || null,
        passwordHash: await hashPassword(tempPassword),
        platformRole: "ORGANIZER",
        emailVerified: true,
      },
    });
  } else if (!isOrganizer(user)) {
    user = await db.user.update({ where: { id: user.id }, data: { platformRole: "ORGANIZER", emailVerified: true } });
  }

  // Organization: reuse the user's own org when they have one, else create it.
  const orgId = await ensureOwnOrg(user, draft!.orgName);

  const conf = await createConferenceForUser(user.id, orgId, basics);
  await db.onboardingDraft.update({ where: { id: draft!.id }, data: { status: "COMPLETED" } });
  await audit({ userId: user.id, conferenceId: conf.id, action: "conference.create", entity: "Conference", entityId: conf.id, meta: { via: "start-funnel" } });

  // Welcome email (includes the temporary password for brand-new accounts).
  try {
    if (tempPassword) {
      await sendOnboardingWelcomeEmail({ email: user.email, name: user.name, conferenceName: basics.name, tempPassword });
    } else {
      await sendWelcomeEmail(user.email, user.name, true);
    }
  } catch { /* emails must never block onboarding */ }

  await createSession(user.id);
  const jar = await cookies();
  jar.delete(DRAFT_COOKIE);
  redirect(`/dashboard/c/${conf.id}?welcome=1`);
}

/** Resend a fresh code to the same email. */
export async function resendOnboardingCodeAction(_formData: FormData) {
  const draft = await getDraft();
  if (!draft || !draft.email) redirect("/start/verify?edit=1");
  const code = String(randomInt(100000, 1000000));
  await db.onboardingDraft.update({
    where: { id: draft!.id },
    data: { code, codeExpiresAt: new Date(Date.now() + CODE_TTL_MIN * 60_000), attempts: 0 },
  });
  const draftBasics = parseJSON<Basics>(draft!.data, {} as Basics);
  const result = await sendOnboardingCodeEmail({
    email: draft!.email!, name: draft!.name ?? "there", code,
    conferenceName: draftBasics.name ?? "your conference",
    expiresMinutes: CODE_TTL_MIN,
  });
  const devHint = result !== "SENT" && process.env.NODE_ENV !== "production" ? `&dev=${code}` : "";
  redirect(`/start/verify?sent=1&resent=1${devHint}`);
}
