import { ResolvingMetadata } from "next";
import { stripHtml } from "./common";

export function getSeoDescription(
  searchDescription?: string | null,
  excerpt?: string | null,
  lead?: string | null
): string | undefined {
  if (searchDescription && searchDescription.length) {
    return searchDescription;
  }
  if (excerpt) {
    const textOnly = stripHtml(excerpt).trim();
    if (textOnly.length) {
      return textOnly;
    }
  }
  if (lead) {
    const textOnly = stripHtml(lead).trim();
    if (textOnly.length) {
      return textOnly;
    }
  }
  return undefined;
}

export async function getSeoMetadata(page: any, parent: ResolvingMetadata) {
  const title = page.seoTitle ?? page.title;
  const description = getSeoDescription(
    page?.searchDescription,
    page?.excerpt,
    page?.lead
  );
  const parentOpenGraph = (await parent)?.openGraph ?? {};
  let images = [];
  if (page?.featuredImage && page.featuredImage.url) {
    images.push(page.featuredImage.url);
  }
  if (page?.logo && page.logo.url) {
    images.push(page.logo.url);
  }
  const openGraph = {
    ...parentOpenGraph,
    title: title,
    description: description,
    images: images,
  };

  return { title, description, openGraph };
}
