import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { supabase } from "@/lib/supabase";
import { QrStandGeneratorClient } from "@/components/QrStandGeneratorClient";
import { DEMO_RESTAURANT, DEMO_CATEGORIES } from "@/lib/demo-data";

type PageProps = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  return {
    title: `${slug} | Masa Stant QR Kod Jeneratörü | Menulio`,
    description: "Restoranınız için yüksek kalitede baskıya hazır A5 masa kartı ve QR stant tasarımları oluşturun.",
  };
}

export default async function RestaurantQrPage({ params }: PageProps) {
  const { slug } = await params;

  if (slug === "demo" || slug === "gusto-brasserie") {
    return (
      <QrStandGeneratorClient
        restaurantName={DEMO_RESTAURANT.name}
        logoUrl={DEMO_RESTAURANT.logo_url}
        slug={slug}
        categoriesList={DEMO_CATEGORIES.map((c) => c.name)}
      />
    );
  }

  const { data: restaurant } = await supabase
    .from("restaurants")
    .select("id, name, slug, logo_url")
    .eq("slug", slug)
    .maybeSingle();

  if (!restaurant) {
    notFound();
  }

  const { data: menu } = await supabase
    .from("menus")
    .select("id, locations!inner(restaurant_id)")
    .eq("locations.restaurant_id", restaurant.id)
    .maybeSingle();

  let categoryNames: string[] = [];
  if (menu) {
    const { data: categories } = await supabase
      .from("menu_categories")
      .select("name")
      .eq("menu_id", menu.id)
      .eq("is_active", true)
      .order("sort_order", { ascending: true });

    if (categories) {
      categoryNames = categories.map((c) => c.name);
    }
  }

  return (
    <QrStandGeneratorClient
      restaurantName={restaurant.name}
      logoUrl={restaurant.logo_url}
      slug={restaurant.slug}
      categoriesList={categoryNames}
    />
  );
}
