const TerserPlugin = require("terser-webpack-plugin");
const { isProduction, pkg } = require("../config");
const { getProjectTitle } = require("../utils");

module.exports = {
  // minimize: false, // uncomment to debug builds
  minimizer: isProduction
    ? [
        new TerserPlugin({
          extractComments: true,
          terserOptions: {
            compress: {
              drop_console: true,
            },
            output: {
              // the regex should match the one in "./utils/banner.js" to
              // preserve the banner of the current project
              comments: new RegExp(`${getProjectTitle()} v${pkg.version}`),
            },
            // mangle: {
            //   properties: {
            //     keep_quoted: true,
            //     regex: /^_/,
            //     reserved: [],
            //   }
            // }
          },
        }),
      ]
    : [],
  mangleWasmImports: true,
  // chunkIds: "named",

  // // when using HTTP/2 and long term caching
  // splitChunks: {
  //   chunks: "all",
  //   maxInitialRequests: 30,
  //   maxAsyncRequests: 30,
  //   maxSize: 100000
  // },

  // // extract css based on entry: @see https://bit.ly/33cD0px
  // splitChunks: {
  //   cacheGroups: (() => {
  //     function recursiveIssuer(m) {
  //       if (m.issuer) {
  //         return recursiveIssuer(m.issuer);
  //       } else if (m.name) {
  //         return m.name;
  //       } else {
  //         return false;
  //       }
  //     }
  //     const cacheGroups = {};
  //     const path = require("path");
  //     const glob = require("glob");
  //     const paths = require("../paths");
  //     const srcPath = paths.frontend.src.routes;
  //     const files = glob.sync(paths.join(srcPath, "**/*.js"));
  //     files.forEach((filePath) => {
  //       const folderName = path.dirname(path.relative(srcPath, filePath));
  //       const name = `${folderName}`;
  //       cacheGroups[name] = {
  //         name: name,
  //         test: (m) =>
  //           m.constructor.name === 'CssModule' && recursiveIssuer(m) === name,
  //         chunks: 'all',
  //         enforce: true,
  //       }
  //     });
  //     return cacheGroups;
  //   })()
  // }

  // // bundle all css in a single file:
  // splitChunks: {
  //   cacheGroups: {
  //     styles: {
  //       name: 'styles',
  //       test: /\.(css|scss|sass)$/,
  //       chunks: 'all',
  //       enforce: true,
  //     },
  //   },
  // },
};
