'use strict';

const FS = require('../models/FS');
const User = require('../models/User');
const Org = require('../models/Org');
const API = require('../models/API');
const Service = require('../models/Service');
const Instance = require('../models/Instance');
const Code = require('../models/Code');

module.exports = async (config, cli) => {
  const fs = new FS();
  const user = new User();

  const instanceName = config.params[0];

  if (!instanceName) {
    throw new Error('please specify an instance name to create by running "sc create <name>"');
  }

  if ((await fs.isCwdEmpty()) || !(await fs.isProjectDirectory())) {
    throw new Error('package.json not found in the cwd');
  }

  cli.logLogo();
  cli.sessionStart('creating', { timer: true });

  const org = new Org({ user });
  await org.authorize();

  if (!org.accessKey) {
    // not logged in
    throw new Error('please login by running "sc login".');
  }

  if (!org.orgName) {
    // this could happen if using access key env var
    // without setting org in package.json
    throw new Error('please add an "org" property in package.json');
  }

  const api = new API({ org });

  const service = new Service({ api, org }); // todo pass projectFile.name

  const instance = new Instance({
    fs,
    api,
    org,
    service,
    instanceName,
  });

  const code = new Code({
    fs,
    api,
    org,
    service,
    instance,
    isForce: config.force,
  });

  await code.init('create');

  if (code.hasChanged()) {
    await code.deploy();
  }

  cli.log();
  cli.logSuccess(`instance ${cli.styles.bold(instanceName)} created`);

  cli.sessionStop('created', 'success');
};
