/* eslint-disable  import/extensions */
const path = require("path");

const dotenv = require("dotenv");
const svgPlugin = require("esbuild-plugin-svgr");
const { yamlPlugin } = require("esbuild-plugin-yaml");
const {
  nodeModulesPolyfillPlugin,
} = require("esbuild-plugins-node-modules-polyfill");
const rails = require("esbuild-rails");
const { sassPlugin } = require("esbuild-sass-plugin");
const postcss = require("postcss");
const sass = require("sass");

const alias = require("./alias.js");
const { babelPlugin } = require("./plugins/babel.js");
const { entrypointPlugin } = require("./plugins/entrypoint.js");
const {
  packageTranslationsPlugin,
} = require("./plugins/packageTranslations.js");
const { prevalPlugin } = require("./plugins/preval.js");
const { reactGiphyPlugin } = require("./plugins/reactGiphy.js");
const { stripSourcemapsPlugin } = require("./plugins/stripSourcemaps.js");
const { virtualizedPlugin } = require("./plugins/virtualized.js");
const { createDefinitions, entryPoint, build, watch } = require("./utils.js");

const postCssConfig = require("../../../../../postcss.config.js");
const commonResolve = require("../webpack/resolve.js");

const isProduction = process.env.NODE_ENV === "production";
const enableMetafile = process.argv.includes("--analyze");
const isWatchMode = process.argv.includes("--watch");
const assetHost =
  process.env.ASSET_HOST &&
  `https://${process.env.ASSET_HOST.replace(/https?\/\//, "")}`;

dotenv.config({ path: isProduction ? ".env" : ".env.development" });

const config = {
  entryPoints: {
    application: entryPoint("app/javascript/packs/application.js"),
    error: entryPoint("app/javascript/packs/error.js"),
  },
  publicPath: `${assetHost ?? ""}/assets`,
  bundle: true,
  splitting: true,
  metafile: enableMetafile,
  outdir: path.join(process.cwd(), "app/assets/builds"),
  minify: isProduction,
  sourcemap: isWatchMode ? true : "external",
  assetNames: "assets/[name]-[hash].digested",
  chunkNames: "chunks/[name]-[hash].digested",
  plugins: [
    stripSourcemapsPlugin(),
    rails(),
    entrypointPlugin(isWatchMode),
    packageTranslationsPlugin(),
    prevalPlugin(),
    babelPlugin(),
    virtualizedPlugin(),
    reactGiphyPlugin(),
    svgPlugin(),
    nodeModulesPolyfillPlugin({ modules: { events: true, fs: true } }),
    sassPlugin({
      transform: async (source, _resolveDir, filePath) => {
        const { css } = await postcss(postCssConfig.plugins).process(source, {
          from: filePath,
        });

        return css;
      },
      logger: sass.Logger.silent,
    }),
    yamlPlugin(),
  ],
  conditions: ["style"],
  logLevel: isWatchMode ? "info" : "error",
  format: "esm",
  platform: "browser",
  mainFields: ["browser", "module", "main"],
  loader: {
    ".png": "file",
    ".jpeg": "file",
    ".jpg": "file",
    ".svg": "file",
    ".ico": "file",
  },
  external: ["path", "os", "events"],
  alias,
  jsx: "automatic",
  resolveExtensions: [...commonResolve.extensions, ".jsx"],
  define: {
    "process.env.RAILS_ENV": "'development'",
    "process.env.NODE_DEBUG": "'development'",
    ...createDefinitions(process),
    "process.env": "{}",
  },
};

module.exports = { config, build: isWatchMode ? watch : build };
