const defaultConfig = require("@wordpress/scripts/config/webpack.config");
const RemoveEmptyScriptsPlugin = require("webpack-remove-empty-scripts");
const fs = require("fs");
const path = require("path");

const requestedBuildEdition = process.env.CACHE_AUTOPILOT_BUILD;
const proFeaturePanelsPath = path.resolve(
    __dirname,
    "assets/pro-src/js/settings/feature-panels.js",
);
const detectedBuildEdition = fs.existsSync(proFeaturePanelsPath)
    ? "pro"
    : "free";
const buildEdition = requestedBuildEdition || detectedBuildEdition;

if (!["free", "pro"].includes(buildEdition)) {
    throw new Error(`Unsupported Cache Autopilot build edition: ${buildEdition}`);
}

const featurePanelsPath =
    buildEdition === "pro"
        ? proFeaturePanelsPath
        : path.resolve(__dirname, "assets/src/js/settings/feature-panels.js");

module.exports = {
    ...defaultConfig,
    entry: {
        "js/settings": path.resolve(__dirname, "assets/src/js/settings.js"),
        "css/settings": path.resolve(__dirname, "assets/src/scss/settings.scss"),
    },
    output: {
        ...defaultConfig.output,
        path: path.resolve(__dirname, "build"),
        filename: "[name].js",
    },
    resolve: {
        ...defaultConfig.resolve,
        alias: {
            ...(defaultConfig.resolve?.alias || {}),
            "@cache-autopilot/invalidator-settings-feature-panels":
                featurePanelsPath,
        },
    },
    plugins: [
        ...defaultConfig.plugins,
        new RemoveEmptyScriptsPlugin({
            stage: RemoveEmptyScriptsPlugin.STAGE_AFTER_PROCESS_PLUGINS,
        }),
    ],
};
