const Client = require('./commands/Client')
const util = require('./utils')
const { handler: login } = require('./commands/login')

class TrialAccount extends Client {
  constructor (argv) {
    super(argv)
    this.userEmail = argv['user-email']
    this.adminName = argv['admin-user-name']
    this.userPassword = argv['user-password']
    this.adminPassword = argv['admin-password']
    this.endpoint = argv.endpoint
    this.name = argv['customer-name']
    this.plan = util.planOptions(argv.plan)
    this.duration = argv['trial-duration']
    this.individual = !!this.plan.licenseType.includes('individual')
    this.enterpriseDomainName = argv['enterprise-domain']
  }

  async getCouponCode () {
    const parameters = {
      email: this.userEmail,
      name: this.name,
      aggregate: !!this.individual,
      domain: this.individual ? null : `${this.endpoint.replace('https://app', `${this.enterpriseDomainName}`)}`,
      plan: this.plan,
      coupon: null,
      trial: { duration: this.duration },
      skipEmail: true
    }
    /* eslint-disable camelcase */
    const response = await this._fetch('POST', 'v1/billing/invites', parameters)
    const { coupon_code } = response
    return coupon_code
  }

  async subscribeTrial (coupon_code) {
    const subscribeParams = {
      termsOfService: true,
      subscriberInviteCode: coupon_code,
      skipEmail: true,
      password: this.userPassword
    }
    const response = await this._fetch('POST', 'v1/billing/trials/subscribe', subscribeParams)
    const { domainId } = response
    return {
      domainId,
      password: this.userPassword
    }
  }

  async setupTrialUser () {
    await login({
      username: this.adminName,
      password: this.adminPassword,
      endpoint: this.endpoint
    })
    const coupon_code = await this.getCouponCode(this.userEmail, this.endpoint)
    const {
      domainId,
      password
    } = await this.subscribeTrial(coupon_code)
    await login({
      username: this.userEmail,
      password,
      endpoint: this.endpoint
    })
    return {
      user: this.userEmail,
      password,
      domainId
    }
  }
}

module.exports = TrialAccount
