const Client = require('../../clients/Client')
const { handleError } = require('../../error')
const { MAST_API_BASE_PATH } = require('./constants')

/**
 * The test command executes device testing via the test API on corellium-mast.
 *
 * @param yargs
 * @returns {Promise<void>}
 */
async function builder (yargs) {
  yargs
    .option('assessment', {
      alias: 'a',
      type: 'string',
      describe: 'MATRIX assessment id',
      demandOption: true
    })
    // NOTE: only required due to coordinator proxy needing to authenticate access to instance
    .option('instance', {
      alias: 'i',
      type: 'string',
      demandOption: true,
      describe: 'virtual device id',
      default: process.env.INSTANCE
    })
    .option('grep', {
      alias: 'g',
      type: 'string',
      describe: 'Only run tests matching this string or regexp'
    })
    .option('invert', {
      alias: 'n',
      type: 'boolean',
      describe: 'Inverts --grep and --fgrep matches',
      default: false
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output',
      default: false
    })
}

async function handler (argv) {
  const { grep, invert, assessment, instance, verbose } = argv
  const client = new Client(argv)
  try {
    const res = await client._fetch('POST', `${MAST_API_BASE_PATH}/${instance}/assessments/${assessment}/test`, { grep, invert })
    console.log(JSON.stringify(res))
  } catch (error) {
    handleError(error, 'test failed', verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'test',
  describe: 'Execute MATRIX checks for assessment'
}
