import { NextResponse } from "next/server";
import { getShop } from "../lib/getShop";

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

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

    const themeColor = shop.menuColor || "#F4F5F9";
    const logo = shop.logo;

    const icons = [];
    if (logo && logo.trim() !== "") {
      // استفاده از API route برای تبدیل لوگو به مربع
      const logo192Url = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=192`;
      const logo512Url = `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=512`;
      
      icons.push(
        {
          src: logo192Url,
          sizes: "192x192",
          type: "image/png",
          purpose: "any",
        },
        {
          src: logo512Url,
          sizes: "512x512",
          type: "image/png",
          purpose: "any",
        }
      );
    } else {
      icons.push(
        {
          src: "/icons/web-app-manifest-192x192.png",
          sizes: "192x192",
          type: "image/png",
          purpose: "any",
        },
        {
          src: "/icons/web-app-manifest-512x512.png",
          sizes: "512x512",
          type: "image/png",
          purpose: "any",
        }
      );
    }

    const manifest = {
      name: shop.name,
      short_name: shop.name,
      description: shop.description || `فروشگاه ${shop.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":
          "no-store, no-cache, must-revalidate, proxy-revalidate",
        Pragma: "no-cache",
        Expires: "0",
      },
    });
  } catch (error) {
    if (error instanceof Error && error.message === "SHOP_NOT_FOUND") {
      return new NextResponse("Shop not found", { status: 404 });
    }

    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
