const { readProfile } = require('../../profile')

const { displayTable } = require('../../table')
const { getAxios } = 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 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 (error) {
    const errorMessage = error.message || error
    console.error(`List extensions failed: ${errorMessage}`)

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

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