/* eslint-disable @bigbinary/neeto/no-dangling-constants */
const { generateMergedTranslations } = require("./packageTranslations");

// Patterns found in dist files (rollup replaces env vars with actual paths,
// but preval.require() calls remain unevaluated in the dist output)
const DIST_PREVAL_TRANSLATION_IMPORTS =
  /preval\.require\(\s*"[^"]*buildTranslationImports\.js"\s*\)/;

const DIST_PREVAL_ENGLISH_TRANSLATIONS =
  /preval\.require\(\s*"[^"]*getEnglishTranslation\.js"\s*\)/;

// Patterns found in source files (env vars not yet replaced)
const SRC_PREVAL_TRANSLATION_IMPORTS =
  /preval\.require\(\s*process\.env\.GET_TRANSLATION_IMPORTS_PATH\s*\)/;

const SRC_PREVAL_ENGLISH_TRANSLATIONS =
  /preval\.require\(\s*process\.env\.GET_ENGLISH_TRANSLATIONS_PATH\s*\)/;

let cachedEnglishTranslations = null;

const getEnglishTranslationsJSON = () => {
  if (cachedEnglishTranslations !== null) return cachedEnglishTranslations;

  const mergedTranslations = generateMergedTranslations();
  cachedEnglishTranslations = JSON.stringify(
    mergedTranslations.en?.translation || {}
  );

  return cachedEnglishTranslations;
};

const prevalReplace = source => {
  const hasDistPattern =
    DIST_PREVAL_TRANSLATION_IMPORTS.test(source) ||
    DIST_PREVAL_ENGLISH_TRANSLATIONS.test(source);

  const hasSrcPattern =
    SRC_PREVAL_TRANSLATION_IMPORTS.test(source) ||
    SRC_PREVAL_ENGLISH_TRANSLATIONS.test(source);

  if (!hasDistPattern && !hasSrcPattern) return null;

  const englishJSON = getEnglishTranslationsJSON();

  let replaced = source;

  // Replace translation imports with empty object (no lazy-loading in tests/storybook)
  replaced = replaced.replace(DIST_PREVAL_TRANSLATION_IMPORTS, "{}");
  replaced = replaced.replace(SRC_PREVAL_TRANSLATION_IMPORTS, "{}");

  // Replace english translations with merged package translations
  replaced = replaced.replace(
    DIST_PREVAL_ENGLISH_TRANSLATIONS,
    () => englishJSON
  );

  replaced = replaced.replace(
    SRC_PREVAL_ENGLISH_TRANSLATIONS,
    () => englishJSON
  );

  return replaced;
};

module.exports = { prevalReplace };
