import type { Metadata } from 'next';

const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL ?? 'https://gamesji.com').replace(/\/$/, '');
const SITE_NAME = process.env.NEXT_PUBLIC_SITE_NAME ?? 'GamesJi';

interface PageMetaInput {
  title: string;
  description: string;
  path: string; // leading slash, e.g. "/games/minecraft"
  image?: string | null;
  type?: 'website' | 'article';
  noindex?: boolean;
}

export function buildPageMetadata(input: PageMetaInput): Metadata {
  const url = `${SITE_URL}${input.path}`;
  const image = input.image ?? `${SITE_URL}/og-default.png`;

  return {
    title: input.title,
    description: input.description,
    alternates: { canonical: url },
    robots: input.noindex
      ? { index: false, follow: false }
      : { index: true, follow: true, googleBot: { index: true, follow: true, 'max-image-preview': 'large' } },
    openGraph: {
      title: input.title,
      description: input.description,
      url,
      siteName: SITE_NAME,
      images: [{ url: image, width: 1200, height: 630 }],
      type: input.type ?? 'website',
    },
    twitter: {
      card: 'summary_large_image',
      title: input.title,
      description: input.description,
      images: [image],
    },
  };
}

export function truncateForMeta(text: string, maxLen: number): string {
  if (text.length <= maxLen) return text;
  return text.slice(0, maxLen - 1).replace(/\s+\S*$/, '') + '\u2026';
}
