import {
  hreflangMap,
  localizedModePath,
  locales,
  defaultMode,
  type Locale,
  type RouteId,
} from '@/lib/localization/config';
import type { ThemePreference } from '@/lib/theme/config';
import { getSiteOrigin } from '@/lib/localization/site-origin';
import type { Metadata } from 'next';

interface LocalizedMetadataInput {
  locale: Locale;
  mode?: ThemePreference;
  routeId: RouteId;
  title: string;
  description: string;
  indexable: boolean;
}

export function buildLocalizedMetadata({
  locale,
  mode = defaultMode,
  routeId,
  title,
  description,
  indexable,
}: LocalizedMetadataInput): Metadata {
  const origin = getSiteOrigin();
  const publicReleaseApproved = process.env.PUBLIC_RELEASE_APPROVED === 'true';
  const canIndex = publicReleaseApproved && indexable;
  const canonicalPath = localizedModePath(routeId, locale, mode);

  return {
    metadataBase: origin,
    title,
    description,
    alternates: {
      canonical: canonicalPath,
      languages: hreflangMap(origin, routeId, mode),
    },
    openGraph: {
      type: 'website',
      siteName: 'RentalDriveGo',
      title,
      description,
      url: canonicalPath,
      locale,
      alternateLocale: locales.filter((candidate) => candidate !== locale),
    },
    twitter: {
      card: 'summary',
      title,
      description,
    },
    robots: canIndex
      ? { index: true, follow: true }
      : { index: false, follow: false, noarchive: true },
  };
}
