import type { Metadata } from "next";

import { siteConfig } from "@/config/site.config";
import { locales, type Locale } from "@/lib/locales";
import { localizedPath } from "@/lib/routes";

type MetadataInput = {
  locale: Locale;
  title: string;
  description: string;
  path?: string;
  imagePath?: string;
  noIndex?: boolean;
};

export function createMetadata({
  locale,
  title,
  description,
  imagePath,
  noIndex = false,
  path = "",
}: MetadataInput): Metadata {
  const canonical = `${siteConfig.url}${localizedPath(locale, path)}`;
  const image = imagePath
    ? `${siteConfig.url}${imagePath.startsWith("/") ? imagePath : `/${imagePath}`}`
    : `${siteConfig.url}/${locale}/opengraph-image`;
  const languages = Object.fromEntries(
    locales.map((supportedLocale) => [
      supportedLocale,
      `${siteConfig.url}${localizedPath(supportedLocale, path)}`,
    ]),
  );

  return {
    title,
    description,
    metadataBase: new URL(siteConfig.url),
    applicationName: siteConfig.name,
    publisher: siteConfig.name,
    creator: siteConfig.name,
    robots: noIndex
      ? { index: false, follow: true }
      : {
          index: true,
          follow: true,
          googleBot: {
            index: true,
            follow: true,
            "max-image-preview": "large",
            "max-snippet": -1,
            "max-video-preview": -1,
          },
        },
    alternates: {
      canonical,
      languages: {
        ...languages,
        "x-default": `${siteConfig.url}${localizedPath("en", path)}`,
      },
    },
    openGraph: {
      title,
      description,
      url: canonical,
      siteName: siteConfig.name,
      type: "website",
      locale,
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
          alt: `${title} - ${siteConfig.name}`,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [image],
    },
  };
}

export function createBreadcrumbJsonLd(
  locale: Locale,
  items: { name: string; path: string }[],
) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((item, index) => ({
      "@type": "ListItem",
      position: index + 1,
      name: item.name,
      item: `${siteConfig.url}${localizedPath(locale, item.path)}`,
    })),
  };
}
