import type { Metadata } from 'next';
import { SITE, type Lang } from '@/lib/config';
import { buildUrl, getAlternateUrls, getCanonicalUrl } from '@/lib/url';

type BuildPageMetadataOptions = {
  lang: Lang;
  title: string;
  description: string;
  /**
   * Path relative to the language root, e.g. "services" or "/services/roi".
   * Leave empty for the homepage.
   */
  path?: string;
  keywords?: string[];
  image?: string;
  noindex?: boolean;
};

function normalizePath(path?: string): string {
  if (!path || path === '/') return '';
  const withSlash = path.startsWith('/') ? path : `/${path}`;
  return withSlash.replace(/\/+$/, '');
}

export function buildPageMetadata({
  lang,
  title,
  description,
  path,
  keywords,
  image,
  noindex = false,
}: BuildPageMetadataOptions): Metadata {
  const cleanPath = normalizePath(path);
  const canonical = getCanonicalUrl(lang, cleanPath);
  const alternates = getAlternateUrls(cleanPath);
  const ogImage = image
    ? image.startsWith('http')
      ? image
      : buildUrl(image.startsWith('/') ? image : `/${image}`)
    : buildUrl('/opengraph-image');

  return {
    title,
    description,
    keywords,
    alternates: {
      canonical,
      languages: alternates,
    },
    openGraph: {
      title,
      description,
      url: canonical,
      siteName: SITE.brand,
      locale: lang === 'ar' ? 'ar_QA' : 'en_US',
      type: 'website',
      images: [
        {
          url: ogImage,
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: [ogImage],
    },
    robots: {
      index: !noindex,
      follow: !noindex,
      googleBot: {
        index: !noindex,
        follow: !noindex,
      },
    },
  };
}
