import type { Metadata, Viewport } from "next";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { notFound } from "next/navigation";
import {
  buildRestaurantMetadata,
  buildRestaurantViewport,
} from "@/app/[name]/lib/restaurantMetadata";
import { prefetchMenuPageData } from "@/app/[name]/lib/prefetchMenuPage";
import { getQueryClient } from "@/lib/query/getQueryClient";
import MenuIndex from "./components/MenuIndex";

type PageParams = { name: string };

export async function generateMetadata({
  params,
}: {
  params: Promise<PageParams>;
}): Promise<Metadata> {
  const { name } = await params;
  return buildRestaurantMetadata(name);
}

export async function generateViewport({
  params,
}: {
  params: Promise<PageParams>;
}): Promise<Viewport> {
  const { name } = await params;
  return buildRestaurantViewport(name);
}

export default async function Page({
  params,
}: {
  params: Promise<PageParams>;
}) {
  const { name } = await params;
  const queryClient = getQueryClient();

  try {
    await prefetchMenuPageData(queryClient, name);
  } catch (error) {
    if (error instanceof Error && error.message === "RESTAURANT_NOT_FOUND") {
      notFound();
    }
    throw error;
  }

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <MenuIndex />
    </HydrationBoundary>
  );
}
