import type { Metadata } from "next";
import { absoluteUrl } from "@/lib/utils";
import { locales, type Locale } from "@/lib/i18n/config";

type MetaOptions = {
  locale: Locale;
  title: string;
  description: string;
  path?: string;
  image?: string;
  type?: "website" | "article" | "product";
  noIndex?: boolean;
};

export function buildMetadata({
  locale,
  title,
  description,
  path = "",
  image = "/images/hero-main.jpg",
  type = "website",
  noIndex = false,
}: MetaOptions): Metadata {
  const canonical = absoluteUrl(`/${locale}${path}`);
  const languages = Object.fromEntries(
    locales.map((code) => [code, absoluteUrl(`/${code}${path}`)]),
  ) as Record<string, string>;

  return {
    title,
    description,
    alternates: { canonical, languages },
    openGraph: {
      title,
      description,
      url: canonical,
      siteName: "DAR ZELLIGE",
      locale: locale === "fr" ? "fr_MA" : locale === "ar" ? "ar_MA" : "en_US",
      type: type === "product" ? "website" : type,
      images: [{ url: absoluteUrl(image), width: 1200, height: 1200, alt: title }],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [absoluteUrl(image)],
    },
    robots: noIndex ? { index: false, follow: false } : { index: true, follow: true },
  };
}

export function jsonLd(data: Record<string, unknown>) {
  return JSON.stringify(data).replace(/</g, "\\u003c");
}
