import { notFound, redirect } from "next/navigation";
import { db } from "@/lib/db";
import { requireUser } from "@/lib/auth";
import { getLiveFeed } from "@/lib/live";
import { LiveScreen } from "@/components/live/live-screen";

export const metadata = { title: "Live" };

export default async function LiveConferencePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const user = await requireUser();
  const conf = await db.conference.findUnique({ where: { slug }, select: { id: true, status: true } });
  if (!conf || conf.status === "DRAFT") notFound();

  // Gate: registered attendees, conference team, volunteers, or super admin
  const [registration, membership] = await Promise.all([
    db.registration.findFirst({
      where: { conferenceId: conf.id, status: { not: "CANCELLED" }, OR: [{ userId: user.id }, { email: user.email }] },
      select: { id: true },
    }),
    db.confMember.findFirst({ where: { conferenceId: conf.id, userId: user.id }, select: { id: true } }),
  ]);
  if (!registration && !membership && user.platformRole !== "SUPER_ADMIN") {
    redirect(`/c/${slug}/register`);
  }

  const [feed, notes] = await Promise.all([
    getLiveFeed(conf.id),
    db.liveNote.findMany({
      where: { userId: user.id, conferenceId: conf.id },
      orderBy: { createdAt: "desc" },
      include: { update: { select: { title: true, type: true } } },
    }),
  ]);
  if (!feed) notFound();

  return (
    <LiveScreen
      initialFeed={feed}
      userName={user.name}
      initialNotes={notes.map((n) => ({ id: n.id, text: n.text, title: n.update?.title ?? null, at: n.createdAt.toISOString() }))}
    />
  );
}
