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

const journalingRequest = require('./journalingRequest')

async function journaling(companyId, operation, crmPhone, crmAgent, crmCallDuration = 0, crmFirstName ='Username') {
 
    const crmFiles = await loadCRM(companyId) 

    for (const crmConfig of crmFiles) {

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

        let contact = await lookupContactByPhone(rest, authentication, crmPhone, companyId) 
  
        if (!contact.exist) {
            contact = await createContact(companyId, rest, authentication, crmPhone, crmFirstName)
        } 

        let { request, calls, response } = findProperty(rest, 'callJournaling')

        let body = findProperty(calls, operation)

        await journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, rest, companyId)

    }

}

module.exports = journaling


