import { removeLeadingSlash } from 'vuepress/shared';
import { getBundlerName } from './getBundlerName.js';
import { mergeViteConfig } from './vite/index.js';
/**
 * Handle specific path when running VuePress Dev Server
 *
 * @param config VuePress Bundler config
 * @param app VuePress Node App
 * @param path Path to be responded
 * @param response respond function
 * @param errMsg error msg
 */
export const customizeDevServer = (bundlerOptions, app, { errMsg = 'The server encountered an error', response: responseHandler, path, }) => {
    const { base } = app.options;
    const bundlerName = getBundlerName(app);
    // in dev
    if (app.env.isDev) {
        // for vite
        if (bundlerName === 'vite') {
            const viteBundlerOptions = bundlerOptions;
            const handler = (request, response) => {
                responseHandler(request, response)
                    .then((data) => {
                    response.statusCode = 200;
                    response.end(data);
                })
                    .catch(() => {
                    response.statusCode = 500;
                    response.end(errMsg);
                });
            };
            const viteMockRequestPlugin = {
                name: `virtual:dev-server-mock/${path}`,
                configureServer: ({ middlewares }) => {
                    middlewares.use(`${base}${removeLeadingSlash(path)}`, handler);
                },
            };
            viteBundlerOptions.viteOptions = mergeViteConfig(viteBundlerOptions.viteOptions || {}, { plugins: [viteMockRequestPlugin] });
        }
        // for webpack
        else if (bundlerName === 'webpack') {
            const webpackBundlerOptions = bundlerOptions;
            const { devServerSetupMiddlewares } = webpackBundlerOptions;
            webpackBundlerOptions.devServerSetupMiddlewares = (middlewares, server) => {
                server.app?.get(`${base}${removeLeadingSlash(path)}`, (request, response) => {
                    responseHandler(request, response)
                        .then((data) => response.status(200).send(data))
                        .catch(() => response.status(500).send(errMsg));
                });
                return devServerSetupMiddlewares
                    ? devServerSetupMiddlewares(middlewares, server)
                    : middlewares;
            };
        }
    }
};
