import { notFound, redirect } from "next/navigation";

import {
  listBakedFunnelIds,
  peekBakedFunnelDefinition,
} from "@/lib/funnel/loadFunnelDefinition";

export const dynamic = "force-static";

export function generateStaticParams() {
  return listBakedFunnelIds().map((funnelId) => ({ funnelId }));
}

interface FunnelRootPageProps {
  params: Promise<{
    funnelId: string;
  }>;
}

export default async function FunnelRootPage({ params }: FunnelRootPageProps) {
  const { funnelId } = await params;

  let funnel: ReturnType<typeof peekBakedFunnelDefinition>;
  try {
    funnel = peekBakedFunnelDefinition(funnelId);
  } catch (error) {
    console.error(`Failed to load funnel '${funnelId}':`, error);
    notFound();
  }

  const firstScreenId =
    funnel.meta.firstScreenId ?? funnel.screens.at(0)?.id ?? "";

  if (!firstScreenId) {
    redirect("/");
  }

  redirect(`/${funnel.meta.id}/${firstScreenId}`);
}
