import { KeyPrefix, Namespace, i18n } from "i18next";
import { UseTranslationResponse, useTranslation as useI18NextTranslation } from "react-i18next";
import enResources from "../common/locales/en.json";
import esResources from "../common/locales/es.json";
import { MODULE_NAME } from "./manifest";

const addMissingBundles = (i18n: i18n) => {
  const needsEn = !i18n.hasResourceBundle("en", MODULE_NAME);
  const needsEs = !i18n.hasResourceBundle("es", MODULE_NAME);

  if (needsEn) {
    i18n.addResourceBundle("en", MODULE_NAME, enResources, true, true);
  }

  if (needsEs) {
    i18n.addResourceBundle("es", MODULE_NAME, esResources, true, true);
  }
};

export const useTranslation = <
  Ns extends Namespace = typeof MODULE_NAME,
  K extends KeyPrefix<Ns> = undefined,
>(
  keyPrefix?: K
): UseTranslationResponse<Ns, K> => {
  const { i18n } = useI18NextTranslation();
  addMissingBundles(i18n);
  return useI18NextTranslation(MODULE_NAME, { keyPrefix });
};
