import path from 'path';
import { createFolderIfItDoesNotExist, doesFileExist } from '../utils/file-utils.js';
import DeploymentValidator from '../validators/deployment-validator.js';
import { GENERATOR_NAME, writeConfigFile } from './export-utils.js';
export default function exportDeployments(deployments) {
    if (!deployments) {
        throw new Error('Deployments have to be passed to be exported.');
    }
    return Object.values(deployments).map(deployment => {
        checkForErrors(deployment);
        deployment = setUpDeploymentStructure(deployment);
        writeDeploymentConfigs(deployment);
        return deployment;
    });
}
function checkForErrors(deployment) {
    const validator = new DeploymentValidator();
    validator.validate(deployment);
}
function setUpDeploymentStructure(deployment) {
    let deploymentToExport = {};
    deploymentToExport[GENERATOR_NAME] = JSON.parse(JSON.stringify(deployment, null, 2).concat('\n'));
    deploymentToExport[GENERATOR_NAME].appsFolders = deployment.appsFolders;
    deploymentToExport[GENERATOR_NAME].clusteredDbApps = deployment.clusteredDbApps;
    deploymentToExport = setUpArrayOptions(deploymentToExport);
    return deploymentToExport;
}
function setUpArrayOptions(deployment) {
    deployment[GENERATOR_NAME].appsFolders = Array.from(deployment[GENERATOR_NAME].appsFolders);
    deployment[GENERATOR_NAME].clusteredDbApps = Array.from(deployment[GENERATOR_NAME].clusteredDbApps);
    return deployment;
}
function writeDeploymentConfigs(deployment) {
    const folderName = deployment[GENERATOR_NAME].deploymentType;
    if (doesFileExist(folderName)) {
        throw new Error(`A file named '${folderName}' already exists, so a folder of the same name can't be created for the application.`);
    }
    createFolderIfItDoesNotExist(folderName);
    writeConfigFile(deployment, path.join(folderName, '.yo-rc.json'));
}
