import { defaultSEOConfig } from "@/config/seoConfig";
import { SITE_URL } from "@/config/pageSeo";
import { Metadata } from "next";

interface PageMetadataOptions {
  title: string;
  description: string;
  path: string;
  type?: "website" | "article" | "profile";
  publishedTime?: string;
  modifiedTime?: string;
  imageUrl?: string;
  imageAlt?: string;
  keywords?: string[];
  /** اگر true باشد « - مدستاگرام» به انتهای عنوان اضافه می‌شود */
  appendSiteName?: boolean;
}

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

export function generatePageMetadata(options: PageMetadataOptions): Metadata {
  const fullUrl = `${SITE_URL}${options.path.startsWith("/") ? options.path : `/${options.path}`}`;

  const finalTitle = options.appendSiteName
    ? `${options.title} | مدستاگرام`
    : options.title;
  const finalDescription = options.description || defaultSEOConfig.description || "";

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

  return {
    title: {
      absolute: finalTitle,
    },
    description: finalDescription,
    keywords: options.keywords,
    alternates: {
      canonical: fullUrl,
    },
    robots: {
      index: true,
      follow: true,
    },
    openGraph: {
      title: finalTitle,
      description: finalDescription,
      url: fullUrl,
      siteName: defaultSEOConfig.openGraph?.site_name || "مدستاگرام",
      locale: "fa_IR",
      type: options.type || "website",
      images,
    },
    twitter: {
      card: "summary_large_image",
      site: defaultSEOConfig.twitter?.site,
      creator: defaultSEOConfig.twitter?.handle,
      title: finalTitle,
      description: finalDescription,
      images: images.map((img) => img.url),
    },
    ...(options.type === "article" &&
    options.publishedTime &&
    options.modifiedTime
      ? {
          article: {
            publishedTime: options.publishedTime,
            modifiedTime: options.modifiedTime,
          },
        }
      : {}),
  };
}
