/* eslint-disable @bigbinary/neeto/no-dangling-constants */
/* eslint-disable  import/extensions */
const getTranslationImports = require("../../scripts/buildTranslationImports.js");
const getEnglishTranslations = require("../../scripts/getEnglishTranslation.js");

const PREVAL_IMPORT_TRANSLATION_IMPORTS =
  'preval.require("../../configs/scripts/buildTranslationImports.js")';

const PREVAL_IMPORT_ENGLISH_TRANSLATIONS =
  'preval.require("../../configs/scripts/getEnglishTranslation.js")';

const SOURCEMAP_URL_RE = /\/\/[#@] sourceMappingURL=[^\n]+/gm;

const prevalPlugin = () => ({
  name: "preval-plugin",
  setup(build) {
    build.onLoad(
      {
        filter:
          /node_modules\/@bigbinary\/neeto-commons-frontend\/dist\/(cjs\/)?(v2\/)?initializers\/i18n.js/,
      },
      async args => {
        const fs = require("fs").promises;
        const contents = await fs.readFile(args.path, "utf8");

        const transformedContent = contents
          .replace(SOURCEMAP_URL_RE, "")
          .replace(PREVAL_IMPORT_TRANSLATION_IMPORTS, getTranslationImports())
          .replace(
            PREVAL_IMPORT_ENGLISH_TRANSLATIONS,
            JSON.stringify(getEnglishTranslations())
          );

        return { contents: transformedContent, loader: "js" };
      }
    );
  },
});

module.exports = { prevalPlugin };
