import type { Metadata } from "next";
import { absoluteUrl, siteConfig } from "@/lib/site";

interface PageMetadataInput {
  /** Title without brand suffix. */
  title: string;
  description: string;
  path: string;
  /** Key of the generated Open Graph image (see src/app/og/[key]/route.tsx). */
  ogKey: string;
  type?: "website" | "article";
  /** Use the title as-is (the home page already contains the brand). */
  absoluteTitle?: boolean;
  publishedTime?: string;
  modifiedTime?: string;
  noindex?: boolean;
}

export const ogImageSize = { width: 1200, height: 630 } as const;

export function ogImagePath(key: string): string {
  return `/og/${key}`;
}

/**
 * Builds complete per-page metadata. Open Graph and Twitter objects are always
 * written in full because Next.js merges metadata shallowly between segments.
 */
export function pageMetadata(input: PageMetadataInput): Metadata {
  const fullTitle = input.absoluteTitle ? input.title : `${input.title} · ${siteConfig.name}`;
  const image = {
    url: ogImagePath(input.ogKey),
    width: ogImageSize.width,
    height: ogImageSize.height,
    alt: fullTitle,
  };

  return {
    title: input.absoluteTitle ? { absolute: input.title } : input.title,
    description: input.description,
    alternates: { canonical: input.path },
    openGraph: {
      type: input.type ?? "website",
      url: input.path,
      siteName: siteConfig.name,
      locale: "en_US",
      title: fullTitle,
      description: input.description,
      images: [image],
      ...(input.type === "article"
        ? {
            publishedTime: input.publishedTime,
            modifiedTime: input.modifiedTime ?? input.publishedTime,
            authors: [siteConfig.name],
          }
        : {}),
    },
    twitter: {
      card: "summary_large_image",
      title: fullTitle,
      description: input.description,
      images: [image.url],
    },
    robots: input.noindex ? { index: false, follow: true } : { index: true, follow: true },
  };
}

export { absoluteUrl };
