const loadCRM = require('./loadCRM')
const lookupContactByPhone = require('./lookupCRMContactByPhone')
const findProperty = require('./findProperty')
const axios = require('axios')
const requestConfigHeader = require('./requestConfigHeader')

async function sfCaseUpdate(companyId, caseId, caseUpdate) {

    const crmFiles = await loadCRM(companyId)

    for (const crmConfig of crmFiles) {

        const { crmRest: rest, authentication } = crmConfig.crm

        let createCase = findProperty(rest, 'createCase')

        console.log('===============> createCase: ', createCase)

        if (createCase) {

            let { request, body } = createCase

            console.log("====> request: ", request)
            console.log("====> body: ", body)

            const { type, userName, passWord, token, crmClientId } = authentication
            const { requestContentType, requestEncoding, requestType, responseType, url } = request

            let config = await requestConfigHeader(url, "17999999999", requestType, requestContentType, type, userName, passWord, token, crmClientId, body)


            config = {
                ...config, ...{
                    method: "Patch",
                    url: `${url}/${caseId}`,
                    data: { ...caseUpdate }
                }
            }

            try {
                const { data } = await axios(config)

                console.log('Data from case updated: ', JSON.stringify(data, null, 6))

                return true

            } catch (error) {
                console.log(`CASE UPDATED ERROR: `, error)
            }
        }

    }

    return false

}

module.exports = sfCaseUpdate