import { EMULSIFY_PROJECT_CONFIG_FILE } from '../../lib/constants.js';
import findFileInCurrentPath from '../fs/findFileInCurrentPath.js';
import writeToJsonFile from '../fs/writeToJsonFile.js';
import getEmulsifyConfig from './getEmulsifyConfig.js';
function isMergeableObject(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function mergeDeepRight(left, right) {
    const result = {
        ...left,
    };
    for (const [key, rightValue] of Object.entries(right)) {
        const leftValue = result[key];
        result[key] =
            isMergeableObject(leftValue) && isMergeableObject(rightValue)
                ? mergeDeepRight(leftValue, rightValue)
                : rightValue;
    }
    return result;
}
export default async function setEmulsifyConfig(config) {
    const path = findFileInCurrentPath(EMULSIFY_PROJECT_CONFIG_FILE);
    const existingConfig = await getEmulsifyConfig();
    if (!path || !existingConfig) {
        throw new Error(`Unable to set values for ${EMULSIFY_PROJECT_CONFIG_FILE} because you are not in an Emulsify project`);
    }
    await writeToJsonFile(path, mergeDeepRight(existingConfig, config));
}
