import type { BackendModule, i18n as I18nInstance } from "i18next";

import { normalizeAdminLanguage } from "@/i18n/languages";
import type { AdminLanguage } from "@/i18n/languages";
import { loadAdminLanguageBundle } from "@/i18n/load-language-bundle";

const pendingLoads = new Map<AdminLanguage, Promise<void>>();

export function ensureAdminLanguageLoaded(i18n: I18nInstance, language: AdminLanguage): Promise<void> {
  if (language === "zh" || i18n.hasResourceBundle(language, "common")) {
    return Promise.resolve();
  }

  const existing = pendingLoads.get(language);
  if (existing) {
    return existing;
  }

  const load = loadAdminLanguageBundle(language).then((bundle) => {
    for (const [namespace, data] of Object.entries(bundle)) {
      i18n.addResourceBundle(language, namespace, data, true, true);
    }
  });

  pendingLoads.set(language, load);
  return load;
}

export function createAdminLanguageBackend(i18n: I18nInstance): BackendModule {
  return {
    type: "backend",
    init() {},
    read(language, namespace, callback) {
      const lang = normalizeAdminLanguage(language);
      void ensureAdminLanguageLoaded(i18n, lang)
        .then(() => callback(null, i18n.getResourceBundle(lang, namespace) ?? {}))
        .catch((error: Error) => callback(error, null));
    },
  };
}
