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

async function sfcase(companyId, crmPhone) {

    const crmFiles = await loadCRM(companyId)

    let res = { contactId: "" }

    for (const crmConfig of crmFiles) {

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

        let createCase = findProperty(rest, 'createCase')

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

        if (createCase) {

            let contact = await lookupContactByPhone(rest, authentication, crmPhone, companyId, {}, false)

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

            if (!contact?.exist) {
                console.log('===============> ContactExist: ', JSON.stringify(contact, null, 6))
                break
            }

            const { contactId, created } = contact

            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

            const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body)

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

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

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

                res.contactId = contactId
                res.caseId = data.id

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

        break

    }

    return res

}

module.exports = sfcase