const axios = require('axios')

/// /////////////////////////////////////////////////////////////////////////////////////////////////// verity WebService
const {
  // verity
  verityBaseUrl,
  verityTokenUrl,
  // VerityUserGroupId,
  VerityBusinessCategoryId,
  // VerityStockAreaId,
  verityAccount,

  // panatech
  panatechBaseUrl,
  panatechTokenUrl,
  // PanatechUserGroupId,
  PanatechBusinessCategoryId,
  // PanatechStockAreaId,
  panatechAccount
} = require('./_env')

// get verity token
let verityToken = ''
module.exports.getVerityToken = async () => {
  try {
    const getToken = await axios.get(verityTokenUrl, { params: verityAccount })
    verityToken = getToken.data
    console.log(verityToken)
  } catch (err) {
    console.log(err)
  }
}

const verityAxiosConfig = () => {
  return {
    baseURL: verityBaseUrl,
    headers: {
      Authorization: verityToken
    }
  }
}

// export verity values
module.exports.verityAxiosConfig = verityAxiosConfig

/// /////////////////////////////////////////////////////////////////////////////////////////////////// panatech WebService

// get panatech token
let panatechToken = ''
module.exports.getPanatechToken = async () => {
  try {
    const getToken = await axios.get(panatechTokenUrl, { params: panatechAccount })
    panatechToken = getToken.data
    console.log(panatechToken)
  } catch (err) {
    console.log(err)
  }
}

const panatechAxiosConfig = () => {
  return {
    baseURL: panatechBaseUrl,
    headers: {
      Authorization: panatechToken
    }
  }
}

// export panatech values
module.exports.panatechAxiosConfig = panatechAxiosConfig

/// /////////////////////////////////////////////////////////////////////////////////////////////////// methods
function axiosConfig(db) {
  if (db === 'verity') return verityAxiosConfig()
  else if (db === 'panatech') return panatechAxiosConfig()
  else return {}
}

function BusinessCategoryId(db) {
  if (db === 'panatech') return PanatechBusinessCategoryId
  else if (db === 'verity') return VerityBusinessCategoryId
  else return null
}

module.exports.saveTransactionToArpa = (data, items, db) => {
  // add static values to data
  data.TransactionID = 'null'
  data.BusinessCode = 'null'
  data.DocAliasID = 144
  data.TrMessage = ''

  const ArpaData = {
    Data: data,
    Items: items
  }

  // @example
  // const arpaExample = {
  //   "Data": {"TransactionID": null, "BusinessID": 3, "DocAliasId": 144, "Description": "تست", "cAddress1": "تهران", "cTel1": "0218884455", "TransCCustom1": "آقای موسوی"},
  //   "Items": [{"TransLineID": null, "itemId": 5302, "MjQty": 20, "StockAreaId": 1}, {"TransLineID": null, "itemId": 5302, "MjQty": 20, "StockAreaId": 1}]
  // }
  
  return new Promise(async (resolve, reject) => {
    try {
      const transaction = await axios.post('/api/NewTransaction', ArpaData, axiosConfig(db))
      const ArpaResponse = transaction.data

      if (ArpaResponse.data) resolve(ArpaResponse.data[0].TransNumber)
      else reject(ArpaResponse.error || 'ARPA WebService Error')
    } catch (e) {
      reject(e)
    }
  })
}

module.exports.saveUserToArpa = (userData, db) => {
  const data = {
    BusName: userData.first_name + ' ' + userData.last_name + ' (گارانتی سایت) ',
    Email: userData.email,
    PhoneNo: userData.tel_number,
    Mobile: userData.mobile_number,
    Name: userData.first_name,
    Family: userData.last_name,
    NationalCode: userData.national_code,
    ProvinceId: userData.province_id,
    CityId: userData.city_id,
    Address: userData.address,
    PostalCode: userData.postal_code,
    BusinessCategoryId: BusinessCategoryId(db),
    CheckExistNationalCode: true
  }

  return new Promise(async (resolve, reject) => {
    try {
      const ArpaID = await axios.get('/api/postBusiness', { ...axiosConfig(db), params: { ...data } })
      if (!ArpaID.data.data) return reject(new Error('Cant save new user -- There is a problem in ArpaWebService'))

      resolve({
        businessID: ArpaID.data.data.BusinessId,
        businessCode: ArpaID.data.data.BusinessCode
      })
    } catch (e) {
      reject(e)
    }
  })
}

module.exports.updateUserOnArpa = (userData, arpa_businessID, db) => {
  const data = {
    BusName: userData.first_name + ' ' + userData.last_name + ' (گارانتی سایت) ',
    Email: userData.email,
    PhoneNo: userData.tel_number,
    Mobile: userData.mobile_number,
    Name: userData.first_name,
    Family: userData.last_name,
    NationalCode: userData.national_code,
    ProvinceId: userData.province_id,
    CityId: userData.city_id,
    Address: userData.address,
    PostalCode: userData.postal_code,
    BusinessCategoryId: BusinessCategoryId(db),
    BusinessID: arpa_businessID,
    CheckExistNationalCode: true
  }

  return new Promise(async (resolve, reject) => {
    try {
      const ArpaUpdate = await axios.post('/api/putBusiness', data, axiosConfig(db))
      if (!ArpaUpdate.data.status) reject(new Error('Cant update user -- There is a problem in ArpaWebService'))
      resolve('updated successfully')
    } catch (e) {
      reject(e)
    }
  })
}
