const axios = require('axios').default
const { readProfile } = require('../profile')

/**
 * Client Base class
 */
class Client {
  constructor (argv) {
    this.argv = Object.assign({}, argv)
    this.project = argv.project || argv.projectId
    this.instance = argv.instance || argv.instanceId
    this._profile = readProfile()
  }

  /**
   * Perform HTTP transaction
   * @protected
   * @param {string} method
   * @param {string} path
   * @param {object} data
   * @returns {Promise<any>}
   */
  _fetch = async (method, path, data) => {
    const headers = {
      Authorization: `Bearer ${this._profile.token}`,
      'User-Agent': `corellium-cli v${require('../../package.json').version}`
    }
    let response
    switch (method) {
      case 'GET':
        response = await axios.get(`${this._profile.endpoint}/api/${path}`, { headers })
        break
      case 'POST':
        response = await axios.post(`${this._profile.endpoint}/api/${path}`, data, { headers })
        break
      case 'DELETE':
        response = await axios.delete(`${this._profile.endpoint}/api/${path}`, { headers })
        break
    }
    if (response.status >= 400) { throw new Error(response.statusText) }
    return response.data || {}
  }
}

module.exports = Client
