import { routing } from '@/i18n/routing'

/**
 * Builds the `alternates` object for Next.js Metadata.
 *
 * @param locale  - The locale of the current page (from params.locale)
 * @param pagePath - The locale-independent path, e.g. '/pricing' or '/guides/geo-pricing-hotels'
 *
 * Returns a canonical URL that is self-referencing (includes the locale prefix
 * for non-default locales) and per-locale hreflang entries for all 21 supported
 * locales plus `x-default` and generic `en`.
 *
 * This is used by every non-homepage page's generateMetadata so that the
 * correct alternates are always emitted regardless of how Next.js renders the
 * segment (static generation, ISR, or SSR).
 */
export function buildAlternates(locale: string, pagePath: string) {
  const languages: Record<string, string> = {}
  for (const loc of routing.locales) {
    const prefix = loc === routing.defaultLocale ? '' : `/${loc}`
    languages[loc] = pagePath === '/' ? (prefix || '/') : `${prefix}${pagePath}`
  }
  // x-default signals the preferred fallback for unmatched locales (English).
  languages['x-default'] = pagePath === '/' ? '/' : pagePath
  // Generic 'en' covers all English-speaking markets (US, AU, CA, etc.).
  languages['en'] = languages[routing.defaultLocale]

  // Self-referencing canonical: include the locale prefix for non-default locales.
  const localePrefix = locale === routing.defaultLocale ? '' : `/${locale}`
  const canonical = pagePath === '/' ? (localePrefix || '/') : `${localePrefix}${pagePath}`

  return { canonical, languages }
}
