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

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

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

  const projectId = argv.projectId

  const projectUrl = profile.endpoint + `/api/v1/projects/${projectId}`

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

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

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

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