import { Metadata } from "next";
import { unescapeHtml } from "./unescapeHtml";
import { stripHtmlTags } from "./stripHtmlTags";
import { DEFAULT_OG_IMAGE, SITE_NAME } from "./constants";

/**
 * Generate generic meta information from WP API
 */
export const generateMeta = (postArray: any, pathPrefix: string = ""): Metadata => {
  const post = postArray?.[0];
  if (!post) return {};

  const wpTitle = post.acf?.meta_title || post.title?.rendered || SITE_NAME;
  const title = unescapeHtml(wpTitle);

  const wpDescription = post.acf?.meta_description || "";
  const description = stripHtmlTags(unescapeHtml(wpDescription));

  const finalTitle = `${title} | ${SITE_NAME}`;
  const finalDescription = description;

  const image = post.featured_media?.source_url || 
                post.featured_image?.source || 
                post.yoast_head_json?.og_image?.[0]?.url || 
                DEFAULT_OG_IMAGE;

  // Build the relative path
  let relativePath = pathPrefix.endsWith('/') ? pathPrefix : `${pathPrefix}/`;
  if (relativePath === '/') relativePath = '';
  const finalPath = `${relativePath}${post.slug}`;
  const canonicalPath = `/${finalPath}`.replace(/\/{2,}/g, "/");

  const metabaseUrl = process.env.SITE_URL;

  const meta: Metadata = {
    metadataBase: new URL(metabaseUrl),
    title: finalTitle,
    description: finalDescription,
    keywords: post.acf?.meta_keywords || "",
    openGraph: {
      title: finalTitle,
      description: finalDescription,
      type: "website",
      siteName: SITE_NAME,
      url: `${process.env.SITE_URL}${finalPath}`,
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: finalTitle,
      description: finalDescription,
      images: [image],
    },
  };

  if (post.acf?.no_index) {
    meta.robots = {
      index: false,
      follow: true,
    };
  } else {
    meta.alternates = {
      canonical: canonicalPath,
    };
  }

  return meta;
};
