const Client = require('../../clients/Client')
const { handleError } = require('../../error')
const { getMastApiBasePath } = require('./api-base-path')

/**
 * Create an assessment via corellium-mast API.
 *
 * @param yargs
 * @returns {Promise<void>}
 */
async function builder (yargs) {
  yargs
    .option('instance', {
      alias: 'i',
      type: 'string',
      demandOption: true,
      describe: 'virtual device id',
      default: process.env.INSTANCE
    })
    .option('bundle', {
      alias: 'b',
      type: 'string',
      demandOption: true,
      describe: 'application bundle id'
    })
    .option('wordlist', {
      alias: 'w',
      type: 'string',
      demandOption: false,
      describe: 'wordlist image id'
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'console will receive verbose error output',
      default: false
    })
}

async function handler (argv) {
  const { instance, bundle, wordlist, verbose } = argv
  const client = new Client(argv)
  try {
    const body = { instanceId: instance, bundleId: bundle, wordlistId: wordlist }
    const API_BASE_PATH = await getMastApiBasePath(client, instance)
    const res = await client._fetch('POST', `${API_BASE_PATH}/${instance}/assessments`, body)
    console.log(JSON.stringify(res))
  } catch (error) {
    handleError(error, 'create-assessment failed', verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'create-assessment',
  describe: 'Create MATRIX assessment for a given instance and application'
}
