import prisma from "@/lib/prisma";
import MenuClient from "../MenuClient";
import { MenuCategory } from "@/data/menu";

async function getMenuData(lang: string): Promise<MenuCategory[]> {
  const dbCategories = await prisma.categories.findMany({
    where: { status: 1 },
    orderBy: { order_num: "asc" },
  });

  const dbProducts = await prisma.products.findMany({
    where: { status: 1 },
    orderBy: [{ category_id: "asc" }, { id: "asc" }],
  });

  return dbCategories.map((cat) => {
    const categoryProducts = dbProducts.filter((p) => p.category_id === cat.id);
    return {
      id: cat.slug,
      title: lang === "tr" ? cat.name_tr : cat.name,
      items: categoryProducts.map((p) => ({
        id: p.id.toString(),
        name: lang === "tr" ? p.name_tr : p.name,
        description: (lang === "tr" ? p.description_tr : p.description) || "",
        price: p.price.toString() + (lang === "tr" ? " ₺" : " ₺"), // Or maybe dynamic currency formatting
        image: p.image_url || '/default-product.png',
      })),
    };
  });
}

async function getSiteSettings() {
  const settingsData = await prisma.settings.findMany()
  const settings = settingsData.reduce((acc, curr) => {
    acc[curr.key] = curr.value
    return acc
  }, {} as Record<string, string>)

  return {
    logoUrl: settings['logo_url'] || '/logo.png',
    location: settings['location'] || 'Akyaka · Muğla',
    restaurantName: settings['restaurant_name'] || 'Kite Beach',
  }
}

export default async function Page({
  params,
}: {
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  
  const [menuData, siteSettings] = await Promise.all([
    getMenuData(lang),
    getSiteSettings(),
  ]);

  return <MenuClient initialCategories={menuData} siteSettings={siteSettings} lang={lang} />;
}
