import prisma from "@/lib/prisma";
import MenuClient from "./MenuClient";
import { MenuCategory } from "@/data/menu";
import { setRequestLocale } from 'next-intl/server';
import { routing } from '@/i18n/routing';

async function getMenuData(locale: 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: (cat.name_i18n as Record<string, string>)?.[locale] || (locale === 'tr' ? cat.name_tr : cat.name),
      items: categoryProducts.map((p) => ({
        id: p.id.toString(),
        name: (p.name_i18n as Record<string, string>)?.[locale] || (locale === 'tr' ? p.name_tr : p.name),
        description: (p.description_i18n as Record<string, string>)?.[locale] || (locale === 'tr' ? p.description_tr : (p.description || '')),
        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({
  params
}: {
  params: Promise<{ locale: string }>
}) {
  const { locale } = await params;
  setRequestLocale(locale);

  const [menuData, siteSettings] = await Promise.all([
    getMenuData(locale),
    getSiteSettings(),
  ]);

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

