'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 Data = require('../models/Data');

module.exports = async (config, cli) => {
  cli.logLogo();
  cli.sessionStart('seeding', { timer: false });

  const fs = new FS();
  const user = new User();
  const api = new API();

  if (!(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 sourceInstanceName = config.source || config.s;
  const destinationInstanceName = config.target || config.t || user.username;

  api.authorize(org);

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

  const destinationInstance = new Instance({
    fs,
    api,
    org,
    service,
    instanceName: destinationInstanceName,
  });

  const destinationData = new Data({
    fs,
    api,
    org,
    service,
    instance: destinationInstance,
  });

  await destinationData.seed(sourceInstanceName);

  let message = `data seeded from the ${cli.styles.bold('data.json')} file to the ${cli.styles.bold(
    destinationInstanceName
  )} instance`;

  if (sourceInstanceName) {
    message = `data seeded from the ${cli.styles.bold(
      sourceInstanceName
    )} instance to the ${cli.styles.bold(destinationInstanceName)} instance`;
  }

  cli.log();
  cli.logSuccess(message);

  cli.sessionStop('seeded');
};
