const { readProfile } = require('../../profile')
const asciiArt = require('ascii-art')
const { getAxios } = require('../../utils')

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.detailedErrors) {
        console.log(res)
      }

      throw new Error(`Status: ${res.status}`)
    }
    console.log(
      asciiArt.style(`Deleted extension ${extensionId}`, 'green', true)
    )
  } catch (error) {
    const errorMessage = error.message || error
    console.error(`Extension delete failed: ${errorMessage}`)

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

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