const path = require('path');
const utils = require('../utils');

module.exports.injectAppConfig = () => {
  return Promise.resolve()
    .then(() => {
      let { configEnvTarget } = utils.getArgs();

      if (!configEnvTarget) {
        throw new Error('configEnvTarget not provided as argument');
      }

      // set default if not envTarget provided
      let envFilePath = path.join(process.cwd(), 'src/assets/config', `env-json-config.json`);

      utils.logInfo(`Executing configuration replacement for : ${configEnvTarget} environment`);

      let envOpenidPrefix = 'env-json-config-';
      let openidConfigAssetsFolder = 'assets/config';

      envFilePath = path.join(process.cwd(), `src/${openidConfigAssetsFolder}`, `${envOpenidPrefix}${configEnvTarget}.json`);

      if (!utils.isFileExists(envFilePath)) {
        utils.logError(`Cannot find environment config to inject : `);
        utils.logError(`${envFilePath} missing...`);
        return;
      }

      let rootTargetFolder = 'src';
      let replacedFile;

      replacedFile = `${rootTargetFolder}/assets/env-json-config.json`;

      utils.logInfo(`Replacing default ${replacedFile} file by ${envFilePath} content`);
      utils.copy(envFilePath, path.join(process.cwd(), `${replacedFile}`));

      utils.logSuccess();
    })

    .catch((e) => {
      throw e;
    });
}