import StorefrontApp from './StorefrontApp';
import type { Metadata } from 'next';
import { db, platformSettings } from '@server/db/drizzle';
import { eq } from 'drizzle-orm';

export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
  title: 'Order',
  robots: { index: false, follow: false },
  viewport: 'width=device-width, initial-scale=1, viewport-fit=cover',
};

interface PageProps {
  params: Promise<{ restaurantSlug: string; branchSlug: string }>;
}

async function getPoweredByConfig(): Promise<{ show: boolean; label: string }> {
  try {
    const rows = await db.select().from(platformSettings).where(eq(platformSettings.key, 'site_title'));
    const v = rows[0]?.value;
    let label = 'Powered by RestroAgent';
    if (typeof v === 'string' && v.trim()) label = `Powered by ${v}`;
    else if (v && typeof v === 'object' && !Array.isArray(v)) {
      const first = Object.values(v as Record<string, unknown>)[0];
      if (typeof first === 'string' && first.trim()) label = `Powered by ${first}`;
    }
    const hideRows = await db.select().from(platformSettings).where(eq(platformSettings.key, 'storefront_hide_powered_by'));
    const hideVal = hideRows[0]?.value;
    const show = !(hideVal === true || hideVal === 'true' || (hideVal && typeof hideVal === 'object' && (hideVal as Record<string, unknown>).enabled === true));
    return { show, label };
  } catch {
    return { show: true, label: 'Powered by RestroAgent' };
  }
}

export default async function Page({ params }: PageProps) {
  const { restaurantSlug, branchSlug } = await params;
  const { show, label } = await getPoweredByConfig();
  return (
    <StorefrontApp
      restaurantSlug={restaurantSlug}
      branchSlug={branchSlug}
      showPoweredBy={show}
      poweredByLabel={label}
    />
  );
}
