import fs from "fs";
import path from "path";
import {defineConfig} from "vite";

const env = process.env || {};
const sites = ["iva", "api"];

const getCustomSitePath = (name, folder) => {
    if (env.npm_config_custom_site) {
        return `../../../custom-sites/${env.npm_config_custom_site}/${name}/${folder}`;
    }
    return folder; // Default path configuration
};

const transformHtmlContent = html => {
    sites.forEach(name => {
        const regex = new RegExp(`{{ ${name.toUpperCase()}_CONFIG_PATH }}`, "g");
        html = html.replace(regex, getCustomSitePath(name, "conf"));
    });
    return html;
};

const configureServer = server => {
    server.middlewares.use((req, res, next) => {
        if (env.npm_config_custom_site && req.url.startsWith("/src/sites") && req.url.includes("img")) {
            const customUrl = req.url.replace("/src/sites", `/custom-sites/${env.npm_config_custom_site}`);
            const originalPath = path.join(process.cwd(), req.url);
            const customPath = path.join(process.cwd(), customUrl);
            if (!fs.existsSync(originalPath) && fs.existsSync(customPath)) {
                req.url = customUrl; // Replace the url with the correct image path
            }
        }
        return next();
    });
};

export default defineConfig({
    mode: env.NODE_ENV || "development",
    root: "./",
    server: {
        open: env.NODE_ENV !== "production"? "/src/sites/iva/index.html": "/iva/index.html",
        port: 3000,
        watch: ["src", "styles", "custom-sites"]
    },
    build: {
        outDir: "build"
    },
    plugins: [
        {
            name: "html-transform",
            transformIndexHtml: transformHtmlContent,
            apply: "serve",
        },
        {
            name: "configure-server",
            configureServer,
            apply: "serve",
        },
    ],
});

@@ -73,16 +73,96 @@
  %22vite%22;
+%0Aimport replace from %22@rollup/plugin-replace%22;%0Aimport pkg from %22./package.json%22;
 %0A%0Aconst 
@@ -1680,32 +1680,280 @@
 ns: %5B%0A        %7B%0A
+            ...replace(%7B%0A                preventAssignment: true,%0A                values: %7B%0A                    %22process.env.VERSION%22: JSON.stringify(pkg.version),%0A                %7D,%0A            %7D),%0A            apply: %22serve%22,%0A        %7D,%0A        %7B%0A
             name

Replace version from env variable in serve #TASK-576