import MiniCssExtractPlugin from "mini-css-extract-plugin";

import type { Contexts } from "@devowl-wp/freemium/webpack";
import {
    applyFreemiumConfigOverride,
    applyFreemiumDefinePlugin,
    applyFreemiumWebpackBarOptions,
} from "@devowl-wp/freemium/webpack";
import { createDefaultSettings } from "@devowl-wp/webpack-config";

function createContextSettings(pluginContext: Contexts) {
    return createDefaultSettings(import.meta.filename, "plugin", {
        override: ([config], factoryValues) => {
            applyFreemiumConfigOverride(pluginContext, config);

            Object.assign(config.externals, {
                tinymce: "tinymce",
                rmlopts: "rmlOpts",
            });

            config.output.library = "[name]";
            config.optimization = {}; // Reset optimization because due to LEGACY purposes

            config.module.rules.push({
                test: /\.less$/,
                exclude: /node_modules\/(?!\.pnpm\/)(?!(antd)).*/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        // See https://github.com/ant-design/ant-design/issues/5440 and https://github.com/ant-design/antd-init/blob/master/examples/local-iconfont/custom.less
                        loader: "string-replace-loader",
                        options: {
                            search: "https://at.alicdn.com/t/font_148784_v4ggb6wrjmkotj4i",
                            replace: "../lib/@devowl-wp/react-folder-tree/src/legacy/fonts/antd-iconfont",
                            flags: "g",
                        },
                    },
                    {
                        loader: "css-loader",
                        options: {
                            url: false,
                        },
                    },
                    {
                        loader: "postcss-loader",
                        options: {
                            postcssOptions: {
                                plugins: ["postcss-preset-env"],
                            },
                        },
                    },
                    {
                        loader: "less-loader",
                        options: {
                            lessOptions: {
                                javascriptEnabled: true,
                            },
                        },
                    },
                ],
            });
        },
        definePlugin: (processEnv) => {
            applyFreemiumDefinePlugin(pluginContext, processEnv);
            return processEnv;
        },
        webpackBarOptions: (options) => {
            applyFreemiumWebpackBarOptions(pluginContext, options);
            return options;
        },
    });
}

export default [createContextSettings("lite"), createContextSettings("pro")].flat();
