const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');

// Default to the free variant so `npm run build` inside the WordPress.org
// package reproduces the shipped build/index.* assets from the included src/.
const isFreeBuild = process.env.STOCKBEACON_BUILD_VARIANT !== 'premium';
const sourceDirectory = process.env.STOCKBEACON_SOURCE_DIR
	? path.resolve(process.env.STOCKBEACON_SOURCE_DIR)
	: path.resolve(__dirname, 'src');
const outputDirectory = process.env.STOCKBEACON_OUTPUT_DIR
	? path.resolve(process.env.STOCKBEACON_OUTPUT_DIR)
	: path.resolve(__dirname, 'build');

// The free bundle keeps the plain "index" name and ships to WordPress.org.
// The premium bundle is emitted as index__premium_only.* so the Freemius
// deployment pipeline removes it from the free version by filename.
const entryName = isFreeBuild ? 'index' : 'index__premium_only';

module.exports = {
	...defaultConfig,
	entry: { [entryName]: path.join(sourceDirectory, 'index.tsx') },
	output: {
		...defaultConfig.output,
		path: outputDirectory,
		// Free and premium assets share build/; cleaning is handled by npm run build.
		clean: false,
	},
	performance: {
		...defaultConfig.performance,
		maxAssetSize: 350000,
		maxEntrypointSize: 350000,
		// Only count assets a browser actually downloads in one page load:
		// index-rtl.css is an alternative to index.css (never loaded together)
		// and *.asset.php is a server-side manifest, never sent to the client.
		assetFilter: (assetFilename) =>
			!/\.map$/.test(assetFilename) &&
			!/-rtl\.css$/.test(assetFilename) &&
			!/\.php$/.test(assetFilename),
	},
	optimization: {
		...defaultConfig.optimization,
		minimizer: [
			new TerserPlugin({
				extractComments: false,
				terserOptions: {
					compress: { passes: 2 },
					mangle: true,
					format: {
						comments: false,
					},
				},
			}),
		],
	},
};
