/**
 * Turning the API's preview model into Next `Metadata` (design D5).
 *
 * One function for both invitation routes. `/i/{token}` and `/e/{slug}` must unfurl
 * identically — that equality is what makes putting meta tags on a tokenized URL safe at
 * all (design D3) — and two call sites building tags by hand is how they would stop being
 * identical six months from now.
 *
 * Nothing here reads a guest. It cannot: `LinkPreviewView` has no guest field, because the
 * API never puts one in it.
 */
import type { Metadata } from "next";

import type { LinkPreviewView } from "./view-models";

export function linkPreviewMetadata(
  preview: LinkPreviewView,
  baseUrl: string | null,
): Metadata {
  // Declared width and height let a chat application reserve the right box before the
  // image arrives, which is the difference between a card that renders and one that
  // shifts. Omitted entirely when the event has no picture — pointing at an image that
  // does not exist gets the whole preview dropped by some platforms.
  const images = preview.image
    ? [
        {
          url: preview.image.url,
          width: preview.image.width,
          height: preview.image.height,
          alt: preview.title,
        },
      ]
    : undefined;

  return {
    // `metadataBase` only ever resolves *relative* URLs, and every URL here arrives from
    // the API already absolute. It is set when configured because Next warns without it,
    // and omitted rather than guessed when it is not (design D7).
    ...(baseUrl ? { metadataBase: new URL(baseUrl) } : {}),
    title: preview.title,
    description: preview.description,
    openGraph: {
      type: "website",
      title: preview.title,
      description: preview.description,
      // The public event page on both routes. A platform caches and attributes the preview
      // against this, so a shared invitation link is never what gets cached.
      url: preview.canonicalUrl,
      siteName: preview.siteName,
      ...(images ? { images } : {}),
    },
    twitter: {
      card: preview.image ? "summary_large_image" : "summary",
      title: preview.title,
      description: preview.description,
      ...(images ? { images } : {}),
    },
  };
}
