import "server-only"

import { createIntl, createIntlCache } from "@formatjs/intl"
import { headers } from "next/headers"

import { Lang } from "@/constants/languages"

const cache = createIntlCache()

async function initIntl(lang: Lang) {
  return createIntl<React.ReactNode>(
    {
      defaultLocale: Lang.en,
      locale: lang,
      messages: (await import(`./dictionaries/${lang}.json`)).default,
    },
    cache
  )
}

export async function getIntl(forceLang?: Lang) {
  const h = headers()
  let lang = h.get("x-lang") as Lang
  if (!lang) {
    lang = Lang.en
  }

  if (forceLang) {
    return await initIntl(forceLang)
  }
  return await initIntl(lang)
}
