import { offerItems as defaultOfferItems } from '~/generated/site/offers'
import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

const OFFER_MODULES = import.meta.glob('../generated/site/offers/index/*.js')
const HAS_OFFER_SPLIT_EXPORT = Object.keys(OFFER_MODULES).length > 0

const offersLocaleExportCache = new Map()

function offerModuleLoader(locale) {
  const normalizedLocale = normalizePublicLocale(locale)

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

function offerModuleLoaderExact(locale) {
  const normalizedLocale = normalizePublicLocale(locale)

  return OFFER_MODULES[`../generated/site/offers/index/${normalizedLocale}.js`] || null
}

async function loadOfferSplitSection(loader, fallbackValue) {
  if (!loader) {
    return fallbackValue
  }

  const module = await loader()
  return module?.offerItems ?? module?.offers ?? fallbackValue
}

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

  if (!offersLocaleExportCache.has(normalizedLocale)) {
    offersLocaleExportCache.set(normalizedLocale, (async () => {
      if (!HAS_OFFER_SPLIT_EXPORT) {
        return Array.isArray(defaultOfferItems) ? defaultOfferItems : []
      }

      const exactLoader = offerModuleLoader(normalizedLocale)
      const exactItems = await loadOfferSplitSection(exactLoader, [])

      if (exactItems.length) {
        return exactItems
      }

      const fallbackLoader = offerModuleLoader(DEFAULT_PUBLIC_LOCALE)
      return loadOfferSplitSection(fallbackLoader, defaultOfferItems)
    })())
  }

  return offersLocaleExportCache.get(normalizedLocale)
}

export async function loadOffersLocaleExportExact(locale = DEFAULT_PUBLIC_LOCALE, fallbackValue = []) {
  const loader = offerModuleLoaderExact(locale)

  if (!loader) {
    return fallbackValue
  }

  const module = await loader()
  return module?.offerItems ?? module?.offers ?? fallbackValue
}
