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']
    })
    .positional('name', {
      type: 'input',
      describe: 'Project name',
      string: true,
      demandOption: true
    })
    .option('cores', {
      type: 'string',
      describe: 'Number of cores to allocate to project',
      demandOption: true
    })
    .option('instances', {
      type: 'string',
      describe: 'Instance quota for project',
      demandOption: true
    })
    .option('ram', {
      type: 'string',
      describe: 'RAM quota for project',
      demandOption: true
    })
}

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

  const cores = argv.cores
  const instances = argv.instances
  const ram = argv.ram
  const name = argv.name

  const projectsUrl = profile.endpoint + '/api/v1/projects'

  const data = {
    name,
    quotas: {
      cores,
      instances,
      ram
    }
  }

  try {
    const axios = await getAxios()
    const res = await axios.post(projectsUrl, data)

    if (res.status !== 200) {
      if (argv.detailedErrors) {
        console.log(res)
      }

      throw new Error(`Status: ${res.status}`)
    }

    displayTable(argv.format, [res.data], ['id'])
  } catch (error) {
    const errorMessage = error.message || error
    console.error(`Project create failed: ${errorMessage}`)

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

module.exports = {
  builder,
  handler,
  command: 'create [cores] [instances] [ram] <name>',
  describe: 'Create project'
}
