const asciiArt = require('ascii-art')
const {
  updateProfile,
  profilePath
} = require('../profile')
const { getErrorMessage } = require('../error')
const {
  validateNonEmpty,
  getCACert
} = require('../utils')
const https = require('https')
const axios = require('axios').default
const prompts = require('prompts')

async function builder (yargs) {
  yargs.option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  }).option('endpoint', {
    type: 'input',
    describe: 'Server endpoint e.g. https://app.corellium.com',
    demandOption: true,
    string: true,
    validateNonEmpty
  }).option('username', {
    type: 'input',
    describe: 'Username',
    demandOption: false,
    string: true,
    validateNonEmpty
  }).option('password', {
    type: 'password',
    describe: 'Password',
    demandOption: false,
    string: true,
    prompt: 'if-no-arg',
    validateNonEmpty
  }).option('apitoken', {
    type: 'password',
    describe: 'API Token',
    demandOption: false,
    string: true,
    validateNonEmpty
  })
}

async function handler (argv) {
  const { username, apitoken, endpoint } = argv
  let { password } = argv

  if (username && !password) {
    password = (await prompts({
      message: 'Enter your password',
      name: 'password',
      type: 'text',
      style: 'invisible'
    })).password
  }

  // We need a special agent just for login because we can't assume profile has been written yet
  const CACert = await getCACert({ endpoint })
  axios.defaults.httpsAgent = new https.Agent({ ca: CACert })

  try {
    let data

    if (apitoken) {
      data = (await axios.post(`${endpoint}/api/v1/tokens`, { apiToken: apitoken })).data
    } else {
      data = (await axios.post(`${endpoint}/api/v1/tokens`, { username, password })).data
    }
    await updateProfile({ token: data.token, expiration: data.expiration, endpoint })
    console.log(asciiArt.style(`Login successful, profile saved to ${profilePath}`, 'green', true))
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`Login failed: ${errorMessage}`)
    if (argv.detailedErrors) { console.log(error) }
  }
}

module.exports = {
  builder,
  handler,
  command: 'login',
  describe: 'Login and save authentication token to local profile.\r\nOptionally supply an API Token instead of credentials.'
}
