import type { Metadata } from "next";

import { getUi, makeT } from "./content";
import { DEFAULT_LOCALE, LOCALES, OG_LOCALE, type Locale } from "./locales";
import { href, type RouteTarget } from "./routes";
import { absoluteUrl, IS_PRODUCTION } from "./site";

/**
 * RRYM / 002 — SULSYS
 * Page metadata. Every page carries a canonical URL and `hreflang` for all
 * four locales plus x-default, which the old site had for none of them
 * (Blueprint 12).
 *
 * x-default points at Albanian — the default tree, and the language of the
 * town the company is in — rather than at English. x-default is "the page to
 * send a reader whose language we cannot determine", not "the international
 * version", and sending an undetermined reader to English would quietly make
 * English the primary site.
 */

type BuildArgs = {
  locale: Locale;
  target: RouteTarget;
  /** Page title without the suffix, e.g. "Nexys System". */
  title: string;
  description: string;
  /** The 404 page is the only route excluded from indexing. */
  noindex?: boolean;
};

export function buildMetadata({
  locale,
  target,
  title,
  description,
  noindex = false,
}: BuildArgs): Metadata {
  const t = makeT(getUi(locale));
  const path = href(target, locale);

  const languages: Record<string, string> = {};
  for (const other of LOCALES) {
    languages[other] = absoluteUrl(href(target, other));
  }
  languages["x-default"] = absoluteUrl(href(target, DEFAULT_LOCALE));

  const fullTitle =
    target.key === "home"
      ? `${title} · ${t("site.companyName")}`
      : `${title} — ${t("meta.suffix")}`;

  return {
    title: fullTitle,
    description,
    alternates: {
      canonical: absoluteUrl(path),
      languages,
    },
    openGraph: {
      type: "website",
      // The company owns the site; the product is named in the title itself.
      siteName: t("site.companyName"),
      locale: OG_LOCALE[locale],
      alternateLocale: LOCALES.filter((other) => other !== locale).map((other) => OG_LOCALE[other]),
      title: fullTitle,
      description,
      url: absoluteUrl(path),
    },
    twitter: {
      card: "summary_large_image",
      title: fullTitle,
      description,
    },
    // Previews are never indexed; neither is the 404 page.
    robots:
      noindex || !IS_PRODUCTION ? { index: false, follow: false } : { index: true, follow: true },
  };
}
