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 proBrandingPath = path.resolve(
    __dirname,
    "assets/pro-src/js/settings/branding.js",
);
const detectedBuildEdition = fs.existsSync(proBrandingPath) ? "pro" : "free";
const buildEdition = requestedBuildEdition || detectedBuildEdition;

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

const brandingPath =
    buildEdition === "pro"
        ? proBrandingPath
        : path.resolve(__dirname, "assets/src/js/settings/branding.js");

module.exports = {
    ...defaultConfig,
    entry: {
        "js/settings": path.resolve(__dirname, "assets/src/js/settings.js"),
        "css/admin": path.resolve(__dirname, "assets/src/scss/admin.scss"),
        "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/warmup-branding": brandingPath,
        },
    },
    plugins: [
        ...defaultConfig.plugins,
        new RemoveEmptyScriptsPlugin({
            stage: RemoveEmptyScriptsPlugin.STAGE_AFTER_PROCESS_PLUGINS,
        }),
    ],
};
