const TrialAccount = require('../TrialAccount')
const { makePassword, validateNonEmpty } = require('../utils')
const { getErrorMessage } = require('../error')
const log = require('../logging')

async function builder (yargs) {
  yargs.options({
    endpoint: {
      type: 'input',
      describe: 'Server endpoint e.g. https://app.ci-4.corellium.co',
      demandOption: true,
      string: true,
      validateNonEmpty
    },
    'admin-user-name': {
      type: 'input',
      describe: 'Admin user',
      demandOption: true,
      string: true,
      validateNonEmpty
    },
    'admin-password': {
      type: 'password',
      describe: 'Admin password',
      demandOption: true,
      string: true,
      prompt: 'if-no-arg',
      validateNonEmpty
    },
    'user-email': {
      type: 'input',
      describe: 'User email',
      demandOption: true,
      string: true,
      validateNonEmpty
    },
    'user-password': {
      type: 'password',
      describe: 'User password',
      demandOption: true,
      string: true,
      prompt: 'if-no-arg',
      mask: true,
      default: makePassword()
    },
    'customer-name': {
      type: 'input',
      describe: 'Customer name. Use company name, unless customer is an individual.',
      demandOption: true,
      string: true
    },
    plan: {
      type: 'list',
      default: 'individual-cloud-3-device',
      describe: 'Plan',
      demandOption: true,
      string: true,
      prompt: 'if-no-arg',
      choices: [
        'individual-cloud-1-device',
        'individual-cloud-3-device',
        'individual-cloud-6-device',
        'enterprise-cloud-6-core',
        'enterprise-cloud-12-core',
        'enterprise-cloud-24-core',
        'individual-cloud-usage-based',
        'enterprise-cloud-usage-based']
    },
    'enterprise-domain': {
      type: 'input',
      describe: 'Enterprise Domain name ',
      demandOption: false,
      string: true,
      default: '',
      prompt: 'if-no-arg',
      when: (args) => args.plan && args.plan.licenseType.includes('enterprise'),
      validateNonEmpty
    },
    'trial-duration': {
      type: 'number',
      demandOption: true,
      number: true,
      describe: 'Trial duration. Default 7 days ',
      default: 7,
      prompt: 'if-no-arg'
    }
  })
}

async function handler (argv) {
  try {
    const trialAccount = new TrialAccount(argv)
    const credentials = await trialAccount.setupTrialUser()
    console.log(credentials)
  } catch (err) {
    const errorMessage = getErrorMessage(err)
    log.error(`Create subscriber invite account: ${errorMessage}`)
    if (argv.detailedErrors) {
      log.error(err)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'signup',
  describe: 'Create subscriber invite account'
}
