import { DEFAULT_LOCALE, LOCALES } from '../config'

const PUBLIC_LOCALIZED_PATHS = ['/', '/about', '/jobs/apply'] as const
const LEGAL_PATHS = [
  '/legal/imprint',
  '/legal/privacy',
  '/legal/terms-and-conditions',
] as const

type SitemapPage = {
  path: string
  sitemap: {
    lastmod: string
    changefreq: 'weekly' | 'monthly' | 'yearly'
    priority: number
    alternateRefs?: Array<{
      href: string
      hreflang: string
    }>
  }
}

function normalizePath(pathname: string): string {
  if (!pathname || pathname === '/') {
    return '/'
  }

  return pathname.startsWith('/') ? pathname : `/${pathname}`
}

function getLocalizedPath(locale: string, pathname = '/'): string {
  const normalizedPath = normalizePath(pathname)

  return normalizedPath === '/'
    ? `/${locale}`
    : `/${locale}${normalizedPath}`
}

const getLocalizedChangeFrequency = (
  pathname: (typeof PUBLIC_LOCALIZED_PATHS)[number]
): SitemapPage['sitemap']['changefreq'] => {
  return pathname === '/' ? 'weekly' : 'monthly'
}

function getAlternateRefs(pathname: (typeof PUBLIC_LOCALIZED_PATHS)[number]) {
  return [
    ...LOCALES.map((locale) => ({
      href: getLocalizedPath(locale, pathname),
      hreflang: locale,
    })),
    {
      href: getLocalizedPath(DEFAULT_LOCALE, pathname),
      hreflang: 'x-default',
    },
  ]
}

export function getSitemapPages(lastModified = new Date()): SitemapPage[] {
  const lastmod = lastModified.toISOString().split('T')[0]!

  const localizedPages: SitemapPage[] = LOCALES.flatMap((locale) =>
    PUBLIC_LOCALIZED_PATHS.map((pathname) => ({
      path: getLocalizedPath(locale, pathname),
      sitemap: {
        lastmod,
        changefreq: getLocalizedChangeFrequency(pathname),
        priority: pathname === '/' ? 1 : 0.8,
        alternateRefs: getAlternateRefs(pathname),
      },
    }))
  )

  const legalPages: SitemapPage[] = LEGAL_PATHS.map((pathname) => ({
    path: getLocalizedPath(DEFAULT_LOCALE, pathname),
    sitemap: {
      lastmod,
      changefreq: 'yearly',
      priority: 0.3,
    },
  }))

  return [
    ...localizedPages,
    ...legalPages,
    {
      path: '/pilot',
      sitemap: {
        lastmod,
        changefreq: 'weekly',
        priority: 0.8,
      },
    },
  ]
}
