import type { Metadata, Viewport } from "next";
import { PWA_ICON_192, PWA_ICON_512 } from "@/lib/helpers/pwaIcons";
import { getRestaurant } from "./getRestaurant";

export async function buildRestaurantMetadata(name: string): Promise<Metadata> {
  const defaultIcon = PWA_ICON_192;
  const defaultIcon512 = PWA_ICON_512;

  try {
    const restaurant = await getRestaurant(name);
    const title = restaurant.seoTitle || restaurant.name;
    // Restaurant logo disabled – using static PWA icons (logo192.png / logo512.png)
    // const logo = restaurant.logo;
    // if (logo && logo.trim() !== "") {
    //   iconUrl = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=192`;
    //   icon192Url = iconUrl;
    //   icon512Url = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=512`;
    // }

    const iconUrl = defaultIcon;
    const icon192Url = defaultIcon;
    const icon512Url = defaultIcon512;

    return {
      title,
      description:
        restaurant.seoDescription ||
        restaurant.description ||
        `منوی ${restaurant.name}`,
      manifest: `/${name}/manifest.webmanifest`,
      icons: {
        icon: [
          { url: iconUrl },
          { url: icon192Url, sizes: "192x192", type: "image/png" },
          { url: icon512Url, sizes: "512x512", type: "image/png" },
        ],
        shortcut: iconUrl,
        apple: iconUrl,
      },
    };
  } catch {
    return {
      title: `${name} - Dashboard`,
      description: `PWA dashboard for ${name}`,
      manifest: `/${name}/manifest.webmanifest`,
      icons: {
        icon: [
          { url: PWA_ICON_192 },
          { url: PWA_ICON_192, sizes: "192x192", type: "image/png" },
          { url: PWA_ICON_512, sizes: "512x512", type: "image/png" },
        ],
        shortcut: PWA_ICON_192,
        apple: PWA_ICON_192,
      },
    };
  }
}

export async function buildRestaurantViewport(name: string): Promise<Viewport> {
  try {
    const restaurant = await getRestaurant(name);
    return {
      themeColor: restaurant.menuColor || "#F4F5F9",
    };
  } catch {
    return {
      themeColor: "#F4F5F9",
    };
  }
}
