const chalk = require('chalk')
const inquirer = require('inquirer')
const { clearConsole } = require('./util/clearConsole')
const { error, stopSpinner, log, logWithSpinner, execa } = require('@vue/cli-shared-utils')

async function aws (enviroment, options = {}, context = process.cwd()) {
  await clearConsole(true)
  const service = options.service || await inquirer.prompt([
    {
      name: 'service',
      type: 'list',
      message: 'Pick the aws service type:',
      choices: [
        { name: 'S3', value: 's3' },
        { name: 'Elastic Beanstalk', value: 'elb' }
      ]
    }
  ]).then(list => list.service)

  log()
  if (service === 's3') {
    logWithSpinner('🔥', 'Generating S3 bucket...')
    await execa(`s3api create-bucket --bucket ${enviroment} --region us-west-1 --create-bucket-configuration LocationConstraint=us-west-1`, { cwd: context })
    stopSpinner()

    logWithSpinner('🎨', 'Enable S3 bucket static website hosting...')
    // await run(`aws s3 website s3://${enviroment}/ --index-document index.html --error-document index.html`)
    stopSpinner()

    logWithSpinner('🔖', 'Enable S3 bucket versioning...')
    // await run(`aws s3api put-bucket-versioning --bucket ${enviroment} --versioning-configuration Status=Enabled`)
    stopSpinner()

    logWithSpinner('📝', 'Uploading S3 Policy to S3 bucket...')
    // await run(`aws s3api put-bucket-policy --bucket ${enviroment} --policy file://policy.json`)
    stopSpinner()
  }

  stopSpinner()
  log()
  log(`🎉  Successfully ${chalk.yellow(enviroment)} is configured.`)
  log()
}

module.exports = (...args) => {
  return aws(...args).catch(err => {
    stopSpinner(false) // do not persist
    error(err)
    if (!process.env.CONTROLLA_CLI_TEST) {
      process.exit(1)
    }
  })
}
