import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";

import type { WebpackBarOptions } from "@devowl-wp/webpack-config";

import type { Configuration, RuleSetRule } from "webpack";

type Contexts = "lite" | "pro";

/**
 * Provide `process.env.PLUGIN_CTX` to your script.
 *
 * @param pluginContext
 * @param processEnv
 */
function applyFreemiumDefinePlugin(pluginContext: Contexts, processEnv: any) {
    processEnv.PLUGIN_CTX = JSON.stringify(pluginContext);
}

/**
 * Rename webpack bar for specific context.
 *
 * @param pluginContext
 * @param options
 */
function applyFreemiumWebpackBarOptions(pluginContext: Contexts, options: WebpackBarOptions) {
    options.name = `${options.name}-${pluginContext}`;
}

/**
 * Apply context-based filenames and libraries and an additional webpack loader to strip
 * pro-specific coding.
 *
 * @param pluginContext
 * @param config
 */
function applyFreemiumConfigOverride(pluginContext: Contexts, config: Configuration) {
    config.name = `${config.name || "default"}-${pluginContext}`;
    config.output.filename = `[name].${pluginContext}.js`;

    // See main WordPress config file comment (same reason why appending query argument)
    config.output.chunkFilename = `[name].${pluginContext}.js?ver=[chunkhash]`;

    const [swcLoader] = config.module.rules as RuleSetRule[];
    if (pluginContext === "lite") {
        (swcLoader.use as any[]).push(import.meta.resolve("./webpack-loader-strip-lite.js").slice(7)); // without file:// protocol

        // In lite version this both plugins are not needed because it is redundant
        config.plugins = config.plugins.filter((plugin) => {
            if (plugin instanceof ForkTsCheckerWebpackPlugin) {
                return false;
            }
            return true;
        });
    }
}

export { type Contexts, applyFreemiumDefinePlugin, applyFreemiumWebpackBarOptions, applyFreemiumConfigOverride };
