const loadCRM = require('./loadCRM')
const lookupContactByPhone = require('./lookupCRMContactByPhone')
const findProperty = require('./findProperty')
const axios = require('axios')
const requestConfigHeader = require('./requestConfigHeader')
const getSalesforceUser = require('./getSalesforceUser')
const { getAccessToken } = require('./oauth2')

async function sfCaseUpdate(companyId, caseId, caseUpdate, agentEmail = null) {

    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, '', companyId)


            config = {
                ...config, ...{
                    method: "Patch",
                    url: `${url}/${caseId}`,
                    data: { ...caseUpdate }
                }
            }
            
            console.log("========> agentEmail: ", agentEmail)
             
            if (agentEmail) {

                const accessToken = await getAccessToken(crmClientId, companyId)
 
                let userData = await getSalesforceUser(accessToken, agentEmail, url)  

                console.log("========> userData: ", userData)

                if (userData && userData?.records?.length > 0){ 
                    config.headers = {...config.headers, ...{"Sforce-Auto-Assign": false}}
                    config.data = { ...config.data, ...{ "OwnerId": userData.records[0].Id } } 
                } 
            }  
 
            try {

                // console.log("=========== payload that will be send to update the case: ", JSON.stringify(config, null, 6))

                const { data } = await axios(config)

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

                return true

            } catch (error) { 

                if (error.response) {
                    console.error('==================> sfCaseUpdate Erro na resposta da API:', {
                        status: error.response.status,
                        data: error.response.data,
                    })
                }
                else if (error.request) {
                    console.error('==================> sfCaseUpdate Nenhuma resposta recebida da API:', error.request)
                }
                else {
                    console.error('==================> sfCaseUpdate Erro ao configurar a request:', error.message)
                }
            }
        }

    }

    return false

}

module.exports = sfCaseUpdate