const { readProfile } = require('../../profile')
const { displayTable } = require('../../table')
const { getAxios } = require('../../utils')
const { handleError } = require('../../error')

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 json) e.g. table',
    string: true,
    choices: ['table', 'json', 'csv']
  })
}

async function handler (argv) {
  const profile = readProfile()
  const extensionsUrl = profile.endpoint + '/api/v1/extensions'
  try {
    const axios = await getAxios()
    const res = await axios.get(extensionsUrl)

    if (!res.data.length) {
      throw new Error('Found no matching Extensions')
    }
    displayTable(argv.format, res.data, [
      'identifier', 'createdAt', 'updatedAt', 'imageId'
    ])
  } catch (err) {
    handleError(err, 'List extensions failed', argv.verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'list',
  aliases: ['ls'],
  describe: 'List all extensions'
}
