// @ts-check

const fs = require("fs");
const path = require("path");

/**
 *
 * @param {HandleEnvVarsFnParams} param0
 * @returns {string}
 */
function handleEnvVars({ json }) {
    let newJson = json;
    try {
        let envVars = { ...process.env };
        const localEnvFilePath = path.resolve(process.cwd(), "./.env");

        if (fs.existsSync(localEnvFilePath)) {
            const localEnvText = fs.readFileSync(localEnvFilePath, "utf8");
            const localEnvKeyPairArray = localEnvText
                .split("\n")
                .filter(
                    (keyPair) =>
                        keyPair &&
                        keyPair.match(/.{3,}/) &&
                        !keyPair.match(/^\#/)
                )
                .map((keyPair) => keyPair.trim());

            localEnvKeyPairArray.forEach((keyPair) => {
                let keyPairArray = keyPair.split("=");
                const key = keyPairArray.shift();
                const value = keyPairArray.join("=");

                const newEnvObject = {};
                newEnvObject[key] = value;

                envVars = { ...envVars, ...newEnvObject };
            });
        }

        for (let key in envVars) {
            newJson = newJson.replaceAll(`$${key}`, String(envVars[key]));
        }
    } catch (error) {
        console.log(`Error replacing Environment variables`, error.message);
        return json;
    }

    return newJson;
}

module.exports = handleEnvVars;
