/* eslint-disable @typescript-eslint/no-var-requires */
const webpack = require("webpack");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const RemovePlugin = require("remove-files-webpack-plugin");

module.exports = (includeRemovePlugin = true) => {
    const plugins = [
        new webpack.DefinePlugin({
            IS_PRODUCTION: true,
            IS_SERVER_SIDE: false,
        }),
    ];
    if (includeRemovePlugin) {
        plugins.push(
            new RemovePlugin({
                before: {
                    root: ".",
                    test: [
                        {
                            folder: "./wwwroot/dist",
                            method: () => true,
                            recursive: true,
                        },
                    ],
                },
            }),
        );
    }

    if (process.env.FAST_BUILD !== "1" || process.env.OUTPUT_BB_STATS) {
        const anaylzerConfig = {
            analyzerMode: "static",
            openAnalyzer: false,
            reportFilename: !includeRemovePlugin
                ? "webpack-bundle-analyzer-shell.html"
                : "webpack-bundle-analyzer.html",
        };

        if (process.env.OUTPUT_BB_STATS) {
            anaylzerConfig.generateStatsFile = true;
            anaylzerConfig.statsOptions = {
                preset: "errors-only",
                errorDetails: true,
                errorStack: true,
                statsFilename: !includeRemovePlugin ? "stats-shell.json" : "stats.json",
            };
        }
        plugins.push(new BundleAnalyzerPlugin(anaylzerConfig));
    }

    return plugins;
};
