import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

const NEWS_INDEX_MODULES = import.meta.glob('../generated/site/news/index/*.js')
const NEWS_BY_SLUG_MODULES = import.meta.glob('../generated/site/news/by-slug/*.js')

export const EMPTY_NEWS_EXPORT = Object.freeze({
  newsArticleBodies: {},
  newsArticles: [],
  newsBodiesBySlug: {},
  newsBySlug: {},
  newsItems: [],
})

const newsLocaleExportCache = new Map()

function newsModuleLoader(modules, section, locale) {
  const normalizedLocale = normalizePublicLocale(locale)

  return modules[`../generated/site/news/${section}/${normalizedLocale}.js`]
    || modules[`../generated/site/news/${section}/${DEFAULT_PUBLIC_LOCALE}.js`]
    || null
}

async function loadNewsModule(modules, section, locale) {
  const loader = newsModuleLoader(modules, section, locale)

  if (!loader) {
    return null
  }

  return loader()
}

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

  if (!newsLocaleExportCache.has(normalizedLocale)) {
    newsLocaleExportCache.set(normalizedLocale, (async () => {
      const [indexModule, bySlugModule] = await Promise.all([
        loadNewsModule(NEWS_INDEX_MODULES, 'index', normalizedLocale),
        loadNewsModule(NEWS_BY_SLUG_MODULES, 'by-slug', normalizedLocale),
      ])

      return {
        newsArticleBodies: indexModule?.newsArticleBodies || {},
        newsArticles: indexModule?.newsArticles || [],
        newsBodiesBySlug: bySlugModule?.newsBodiesBySlug || {},
        newsBySlug: bySlugModule?.newsBySlug || {},
        newsItems: indexModule?.newsItems || [],
      }
    })())
  }

  return newsLocaleExportCache.get(normalizedLocale)
}
