'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');

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

  const instanceName = config.params[0] || user.username;

  cli.logLogo();
  cli.sessionStart('deleting', { timer: false });

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

  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,
  });

  await instance.delete();

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

  cli.sessionStop('deleted');
};
