import i18next from "i18next";
import ICU from "i18next-icu";
import resourcesToBackend from "i18next-resources-to-backend";
import type { Language } from "./resolver.js";

export async function createI18nInstance(options: {
  locale: Language;
  initialResources?: Record<string, Record<string, unknown>>;
}): Promise<typeof i18next> {
  const instance = i18next.createInstance();

  instance.use(ICU);

  // If no pre-loaded resources, load from the locale JSON files on the filesystem.
  if (!options.initialResources) {
    instance.use(
      resourcesToBackend(
        (language: string, namespace: string) =>
          import(`./locales/${language}/${namespace}.json`),
      ),
    );
  }

  await instance.init({
    lng: options.locale,
    ns: ["common"],
    defaultNS: "common",
    fallbackLng: false,
    interpolation: {
      escapeValue: false,
    },
    keySeparator: ".",
    ...(options.initialResources
      ? {
          resources: {
            [options.locale]: options.initialResources,
          },
        }
      : {}),
  });

  return instance;
}
