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

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

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

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

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