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

async function builder (yargs) {
  yargs.positional('extensionId', {
    type: 'string',
    describe: 'Extension ID (UUID)',
    demandOption: true
  }).option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  })
}

async function handler (argv) {
  const profile = readProfile()

  const extensionId = argv.extensionId

  const extensionsUrl = profile.endpoint + `/api/v1/extensions/${extensionId}`

  try {
    const axios = await getAxios()
    const res = await axios.delete(extensionsUrl)

    if (res.status !== 204) {
      if (argv.verbose) {
        console.log(res)
      }

      throw new Error(`Status: ${res.status}`)
    }
    console.log(
      chalk.green(`Deleted extension ${extensionId}`)
    )
  } catch (err) {
    handleError(err, 'Extension delete failed', argv.verbose)
  }
}

module.exports = {
  builder,
  handler,
  command: 'delete <extensionId>',
  aliases: ['rm', 'del'],
  describe: 'Delete extension by id'
}
