const path = require("path");
const TerserPlugin = require('terser-webpack-plugin');
const WebpackObfuscator = require('webpack-obfuscator'); // Import the obfuscator

module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';  // Check if it's production mode

  return {
    entry: {
      background: "./background.js",
      content: "./content.js",
      // Add other scripts if necessary, e.g., popup.js, playerpop.js, etc.
    },
    output: {
      filename: "[name].bundle.js",  // Output files: background.bundle.js, content.bundle.js, etc.
      path: path.resolve(__dirname, "dist"),
    },
    mode: isProduction ? "production" : "development",
    devtool: isProduction ? false : "source-map",  // Disable source maps in production for security

    optimization: {
      minimize: isProduction,  // Minify only in production
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: true,
            mangle: true,  // Mangle variable and function names
            output: {
              comments: false,  // Remove comments
            },
          },
          extractComments: false,  // Prevent extracting comments to separate files
        }),
      ],
    },

    plugins: [
      // Apply obfuscation only in production
      ...(isProduction
        ? [
            new WebpackObfuscator(
              {
                rotateStringArray: true,
                stringArray: true,
                stringArrayThreshold: 1,  // Obfuscate all strings
                stringArrayEncoding: ['base64'],  // Base64 encode strings
                splitStrings: true,  // Split long strings into smaller parts
                selfDefending: true,  // Self-defending code to prevent beautification
                seed: Math.floor(Math.random() * 100000),  // Use a random seed to ensure uniqueness
              },
              ['excluded.bundle.js']  // Optionally exclude certain files
            ),
          ]
        : []),
    ],
  };
};
