import type { Metadata } from "next";
import { fetchApiJson } from "@/lib/api/fetchApiJson";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getServerLanguage } from "@/lib/i18n/server";
import { getSiteSeoMeta } from "@/lib/i18n/seo";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { buildShopJsonLd } from "@/lib/buildShopSeo";
import { SITE_URL } from "@/config/pageSeo";
import ShopProfileClient from "./ShopProfileClient";

interface IShopProfilePageProps {
  params: Promise<{ shopId: string }>;
}

type PublicShop = {
  name: string;
  logo?: string | null;
  description?: string | null;
  has_physical_location?: boolean;
  province?: { name: string } | null;
  city?: { name: string } | null;
  address?: string | null;
  rating?: { average: number; count: number } | null;
};

async function loadShop(shopId: string) {
  const { data } = await fetchApiJson<{ shop?: PublicShop }>(`/shops/public/${shopId}`);
  return data?.shop ?? null;
}

export async function generateMetadata({ params }: IShopProfilePageProps): Promise<Metadata> {
  const { shopId } = await params;
  const lang = await getServerLanguage();
  const site = getSiteSeoMeta(lang);
  const path = `/shops/profile/${shopId}`;

  const shop = await loadShop(shopId);

  if (!shop) {
    const title = `فروشگاه یافت نشد | ${site.titleSuffix}`;
    const meta = generatePageMetadata({
      title,
      description: site.defaultDescription,
      path,
      index: false,
      lang,
    });
    return { ...meta, title: { absolute: title } };
  }

  const title = [shop.name, shop.province?.name, shop.city?.name]
    .filter(Boolean)
    .join(" - ") + ` | ${site.titleSuffix}`;

  const description =
    [
      shop.description,
      shop.address,
      shop.has_physical_location ? "حضوری" : "اینترنتی",
    ]
      .filter(Boolean)
      .join(" - ") || site.defaultDescription;

  const meta = generatePageMetadata({
    title,
    description,
    path,
    type: "website",
    imageUrl: shop.logo ? buildStorageUrl(shop.logo) : undefined,
    imageAlt: shop.name,
    lang,
  });

  return { ...meta, title: { absolute: title } };
}

export default async function ShopProfilePage({ params }: IShopProfilePageProps) {
  const { shopId } = await params;
  const lang = await getServerLanguage();
  const shop = await loadShop(shopId);

  const jsonLd = shop
    ? buildShopJsonLd(
        { ...shop, _id: shopId },
        `${SITE_URL}/shops/profile/${shopId}`,
        lang
      )
    : null;

  return (
    <>
      {jsonLd && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      )}
      <ShopProfileClient />
    </>
  );
}
