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

async function getMenuData(): 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: cat.name_tr,
      items: categoryProducts.map((p) => ({
        id: p.id.toString(),
        name: p.name_tr,
        description: p.description_tr,
        price: p.price.toString() + " ₺",
        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'] || 'Moy Beach',
  }
}

export default async function Page() {
  const [menuData, siteSettings] = await Promise.all([
    getMenuData(),
    getSiteSettings(),
  ]);

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