import { defaultSEOConfig } from "@/config/seoConfig";
import {
  buildLocalizedMetadataFields,
  type LocalizedMetadataInput,
} from "@/lib/i18n/seo";
import { Metadata } from "next";

export interface PageMetadataOptions extends LocalizedMetadataInput {}

const defaultOgImage = defaultSEOConfig.openGraph?.images?.[0];

export function generatePageMetadata(options: PageMetadataOptions): Metadata {
  const localized = buildLocalizedMetadataFields(options);
  const fullUrl =
    typeof localized.openGraph?.url === "string"
      ? localized.openGraph.url
      : undefined;

  const images = options.imageUrl
    ? [
        {
          url: options.imageUrl,
          width: 1200,
          height: 630,
          alt: options.imageAlt || options.title,
        },
      ]
    : defaultOgImage
      ? [defaultOgImage]
      : [];

  const ogTitle =
    options.ogTitle ||
    (typeof localized.openGraph?.title === "string"
      ? localized.openGraph.title
      : options.title);

  return {
    ...localized,
    openGraph: {
      ...localized.openGraph,
      images,
    },
    twitter: {
      card: "summary_large_image",
      site: defaultSEOConfig.twitter?.site,
      creator: defaultSEOConfig.twitter?.handle,
      title: ogTitle,
      description: localized.description,
      images: images.map((img) => img.url),
    },
    ...(options.type === "article" &&
    options.publishedTime &&
    options.modifiedTime
      ? {
          article: {
            publishedTime: options.publishedTime,
            modifiedTime: options.modifiedTime,
          },
        }
      : {}),
  };
}
