import { extras as defaultExtras } from '~/generated/site/extras'
import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

const EXTRAS_MODULES = import.meta.glob('../generated/site/extras/index/*.js')
const HAS_EXTRAS_SPLIT_EXPORT = Object.keys(EXTRAS_MODULES).length > 0

const extrasLocaleExportCache = new Map()

function extrasModuleLoader(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)

  return EXTRAS_MODULES[`../generated/site/extras/index/${normalizedLocale}.js`]
    || EXTRAS_MODULES[`../generated/site/extras/index/${DEFAULT_PUBLIC_LOCALE}.js`]
    || null
}

function normalizeExtrasPayload(value) {
  return Array.isArray(value) ? value : []
}

export async function loadExtrasLocaleExport(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)

  if (!extrasLocaleExportCache.has(normalizedLocale)) {
    extrasLocaleExportCache.set(normalizedLocale, (async () => {
      if (!HAS_EXTRAS_SPLIT_EXPORT) {
        return normalizeExtrasPayload(defaultExtras)
      }

      const directLoader = EXTRAS_MODULES[`../generated/site/extras/index/${normalizedLocale}.js`]

      if (directLoader) {
        const module = await directLoader()

        if (Array.isArray(module?.extras)) {
          return module.extras
        }
      }

      const fallbackLoader = extrasModuleLoader(DEFAULT_PUBLIC_LOCALE)

      if (fallbackLoader) {
        const module = await fallbackLoader()

        if (Array.isArray(module?.extras)) {
          return module.extras
        }
      }

      return normalizeExtrasPayload(defaultExtras)
    })())
  }

  return extrasLocaleExportCache.get(normalizedLocale)
}
