"use server";

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

const BACK = "/dashboard/venues";

export type HallSpec = { name: string; capacity: number | null; floor: string | null };

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

/** Parse the halls textarea: one hall per line as "Name | capacity | floor". */
function parseHalls(raw: string): HallSpec[] {
  return raw
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean)
    .slice(0, 40)
    .map((line) => {
      const [name, capacity, floor] = line.split("|").map((p) => p.trim());
      return { name: name || "Hall", capacity: capacity ? parseInt(capacity, 10) || null : null, floor: floor || null };
    });
}

function venueFields(formData: FormData) {
  const capacity = String(formData.get("capacity") || "").trim();
  return {
    name: String(formData.get("name") || "").trim(),
    address: String(formData.get("address") || "").trim() || null,
    city: String(formData.get("city") || "").trim() || null,
    state: String(formData.get("state") || "").trim() || null,
    capacity: capacity ? parseInt(capacity, 10) || null : null,
    contactName: String(formData.get("contactName") || "").trim() || null,
    contactPhone: String(formData.get("contactPhone") || "").trim() || null,
    contactEmail: String(formData.get("contactEmail") || "").trim() || null,
    website: String(formData.get("website") || "").trim() || null,
    facilities: String(formData.get("facilities") || "").trim() || null,
    mapUrl: String(formData.get("mapUrl") || "").trim() || null,
    description: String(formData.get("description") || "").trim() || null,
    hallsSpec: JSON.stringify(parseHalls(String(formData.get("halls") || ""))),
  };
}

/** Add a venue to the org's reusable venue database. */
export async function createOrgVenue(formData: FormData) {
  const ctx = await requireVenueMutate();
  const fields = venueFields(formData);
  if (!fields.name) redirect(`${BACK}?error=Venue name is required`);
  await db.venue.create({ data: { orgId: ctx.org.id, ...fields } });
  await audit({ userId: ctx.user.id, action: "venue.pool.create", entity: "Venue", meta: { name: fields.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${fields.name} added to your venue database`)}`);
}

/** Edit a pool venue (conference copies are edited inside each conference). */
export async function updateOrgVenue(venueId: string, formData: FormData) {
  const ctx = await requireVenueMutate();
  const venue = await db.venue.findUnique({ where: { id: venueId } });
  if (!venue || venue.orgId !== ctx.org.id || venue.conferenceId) throw new Error("Venue not found in your database.");
  const fields = venueFields(formData);
  await db.venue.update({ where: { id: venueId }, data: { ...fields, name: fields.name || undefined } });
  await audit({ userId: ctx.user.id, action: "venue.pool.update", entity: "Venue", entityId: venueId });
  redirect(`${BACK}?saved=${encodeURIComponent("Venue updated")}`);
}

/** Remove a venue from the database (conference copies stay). */
export async function deleteOrgVenue(venueId: string, _formData: FormData) {
  const ctx = await requireVenueMutate();
  const venue = await db.venue.findUnique({ where: { id: venueId } });
  if (venue && venue.orgId === ctx.org.id && !venue.conferenceId) {
    await db.venue.delete({ where: { id: venueId } });
    await audit({ userId: ctx.user.id, action: "venue.pool.delete", entity: "Venue", entityId: venueId, meta: { name: venue.name } });
  }
  revalidatePath(BACK);
}

/** Use a venue for a conference — copies the profile and creates its halls. */
export async function reuseVenueAction(venueId: string, formData: FormData) {
  const ctx = await requireVenueMutate();
  const targetId = String(formData.get("targetConferenceId") ?? "");
  const [venue, target] = await Promise.all([
    db.venue.findUnique({ where: { id: venueId }, include: { conference: { select: { orgId: true } }, rooms: true } }),
    db.conference.findUnique({ where: { id: targetId }, select: { id: true, orgId: true } }),
  ]);
  const ownerOrgId = venue?.conference?.orgId ?? venue?.orgId;
  if (!venue || ownerOrgId !== ctx.org.id) throw new Error("Venue not found in this organization.");
  if (!target || target.orgId !== ctx.org.id) redirect(`${BACK}?error=Pick a conference`);

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

  // Halls: a conference venue copies its real rooms; a pool venue materializes hallsSpec.
  const halls: HallSpec[] = venue.conferenceId
    ? venue.rooms.map((r) => ({ name: r.name, capacity: r.capacity, floor: r.floor }))
    : parseJSON<HallSpec[]>(venue.hallsSpec, []);

  await db.venue.create({
    data: {
      conferenceId: target.id,
      name: venue.name,
      address: venue.address,
      city: venue.city,
      state: venue.state,
      capacity: venue.capacity,
      contactName: venue.contactName,
      contactPhone: venue.contactPhone,
      contactEmail: venue.contactEmail,
      website: venue.website,
      facilities: venue.facilities,
      description: venue.description,
      mapUrl: venue.mapUrl,
      rooms: {
        create: halls.map((h) => ({ conferenceId: target.id, name: h.name, capacity: h.capacity, floor: h.floor })),
      },
    },
  });
  await audit({ userId: ctx.user.id, conferenceId: target.id, action: "venue.reuse", entity: "Venue", meta: { name: venue.name } });
  redirect(`${BACK}?saved=${encodeURIComponent(`${venue.name} added with ${halls.length} hall${halls.length === 1 ? "" : "s"}`)}`);
}
