const { log } = require('cozy-konnector-libs')
const { isLocal } = require('./env')

function getAccountId() {
  log('info', `getAccountId`)
  try {
    return JSON.parse(process.env.COZY_FIELDS).account
  } catch (err) {
    throw new Error(`You must provide 'account' in COZY_FIELDS: ${err.message}`)
  }
}

function getAccountRev() {
  log('info', `getAccountRev`)
  log('info', `getAccountRev: ${JSON.stringify(process.env.COZY_FIELDS)}`)
  try {
    return isLocal()
      ? 'fakeAccountRev'
      : JSON.parse(process.env.COZY_FIELDS).account_rev
  } catch (err) {
    throw new Error(`You must provide 'account' in COZY_FIELDS: ${err.message}`)
  }
}

/**
 * Return account secrets.
 * For local testing, change value with values from your konnector-dev-config.json
 * @returns {Fields}
 */
function getAccountSecret() {
  log('info', `getAccountSecret`)
  try {
    return isLocal()
      ? JSON.parse(process.env.COZY_FIELDS)
      : JSON.parse(process.env.COZY_PARAMETERS).secret
  } catch (err) {
    throw new Error(
      `You must provide 'account-types' in COZY_PARAMETERS: ${err.message}`
    )
  }
}
module.exports = { getAccountId, getAccountRev, getAccountSecret }