import { NextResponse } from "next/server";
import { buildPwaManifestIcons } from "@/lib/helpers/pwaIcons";
import { getRestaurant } from "../lib/getRestaurant";

export const dynamic = "force-dynamic";
export const revalidate = 0;

function buildManifestIcons(_name: string, _logo?: string | null) {
  // Restaurant logo disabled – using static PWA icons (logo192.png / logo512.png)
  // if (logo && logo.trim() !== "") {
  //   const logo192 = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=192`;
  //   const logo512 = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=512`;
  //   return buildPwaManifestIcons(logo192, logo512);
  // }

  return buildPwaManifestIcons();
}

export async function GET(
  request: Request,
  { params }: { params: Promise<{ name: string }> }
) {
  try {
    const { name } = await params;
    const restaurant = await getRestaurant(name);

    const themeColor = restaurant.menuColor || "#F4F5F9";
    const icons = buildManifestIcons(name, restaurant.logo);

    const manifest = {
      name: restaurant.name,
      short_name: restaurant.name,
      description: restaurant.description || `منوی ${restaurant.name}`,
      start_url: `/${name}`,
      scope: `/${name}`,
      id: `/${name}`,
      display: "standalone",
      display_override: ["fullscreen", "minimal-ui", "browser"],
      background_color: "#F4F5F9",
      theme_color: themeColor,
      orientation: "portrait",
      dir: "rtl",
      lang: "fa-IR",
      icons,
    };

    return NextResponse.json(manifest, {
      headers: {
        "Content-Type": "application/manifest+json",
        "Cache-Control": "public, max-age=300, stale-while-revalidate=600",
      },
    });
  } catch (error) {
    if (error instanceof Error && error.message === "RESTAURANT_NOT_FOUND") {
      return new NextResponse("Restaurant not found", { status: 404 });
    }

    const { name } = await params;
    const manifest = {
      name,
      short_name: name,
      description: `منوی ${name}`,
      start_url: `/${name}`,
      scope: `/${name}`,
      id: `/${name}`,
      display: "standalone",
      display_override: ["fullscreen", "minimal-ui", "browser"],
      background_color: "#F4F5F9",
      theme_color: "#F4F5F9",
      orientation: "portrait",
      dir: "rtl",
      lang: "fa-IR",
      icons: buildManifestIcons(name),
    };

    return NextResponse.json(manifest, {
      headers: {
        "Content-Type": "application/manifest+json",
        "Cache-Control": "public, max-age=300, stale-while-revalidate=600",
      },
    });
  }
}
