const { getErrorMessage } = require('../../error')
const { displayTable } = require('../../table')
const { getApi } = require('../../utils')

async function builder (yargs) {
  yargs.option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is table) e.g. json',
    string: true,
    choices: ['json', 'csv']
  })
}

async function handler (argv) {
  const api = await getApi()
  try {
    const projects = await api.v1GetProjects()
    displayTable(argv.format, projects, ['id', 'name'])
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`List failed: ${errorMessage}`)

    if (argv.detailedErrors) {
      console.log(error)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'list',
  describe: 'List projects'
}
