const log = require('./logging')
function getUserErrorMessage (body) {
  const keys = ['errorID', 'error']
  if (body && body.errorID === 'UserError') {
    const err = Object.keys(body)
      .filter(key => !keys.includes(key))
      .reduce((obj, key) => {
        obj[key] = body[key]
        return obj
      }, {})
    return JSON.stringify(err)
  }
  return ''
}

function getErrorMessage (error) {
  const { body, response, error: errorObject } = error
  if (body && body.error) {
    return `${body.error} ${getUserErrorMessage(body)}`
  } else if (response && response.data && response.data.error) {
    return `${response.data.error} ${getUserErrorMessage(response.data)}`
  } else if (errorObject && errorObject.message) {
    return errorObject.message
  } else {
    return error.message
  }
}

function handleError (error, customMessage, detailed) {
  const errorMessage = getErrorMessage(error)
  console.error(`${customMessage}: ${errorMessage}`)
  if (detailed) { log.error(JSON.stringify(error.body || error.response?.data || error.message, null, 2)) }
  process.exit(1)
}

module.exports = { handleError }
