const loadCRM = require('./loadCRM')
const lookupContactByPhone = require('./lookupCRMContactByPhone')
const createContact = require('./createContact')
const findProperty = require('./findProperty')
const CRM_Contact = require('../models/CRM_Contact')
const CRM_Ticket = require('../models/CRM_Ticket')
const CRM = require('../models/CRM')
const createTicket = require('./createTicket')

const lookupCRMTicket = require('./lookupCRMTicket')
const sendEventTicketCreatedToSocket = require('./sendEventTicketCreatedToSocket')
const journalingRequest = require('./journalingRequest')
 
const getIntegrationsConfig = require('../utils/getIntegrationsConfig')

async function whatsappJournalingCRM(companyId, crmPhone, crmAgent, crmFirstName = 'Username', ticketId = null) {

    const crmFiles = await loadCRM(companyId)

    const crmContactIds = []  

    for (const crmConfig of crmFiles) {

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

        // Record whatsapp conversation that happened in omnihit v2
        let chatJournaling = findProperty(rest, 'chatJournaling')

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


        if (chatJournaling) {

            let contact = await _lookupContact(rest, authentication, crmPhone, companyId, crmFirstName) 

            let { request, chats, response } = chatJournaling

            let body = findProperty(chats, 'chatDone')


            let config = await getIntegrationsConfig(companyId, 'omnihit') 

            if (ticketId && config) {

                const { accountId, api: { url, urlHttps, token } = {},
                    createConversation: { inbox_id, status, team_id } = {} = {} } = config

                console.log('===============> body1: ', body)
                body = JSON.stringify(body)

                if (body.includes('chatLink')) {
                    body = body.replace('chatLink', `${urlHttps}/app/accounts/${accountId}/conversations/${ticketId}`)
                }

                console.log('===============> body2: ', body)
                body = JSON.parse(body)
                console.log('===============> body3: ', body)
            }








            await journalingRequest(request, body, crmCallDuration = 0, contact, crmAgent, crmPhone, authentication, rest, companyId)
        }
        //


    }

    return crmContactIds

}

module.exports = whatsappJournalingCRM


async function _lookupContact(rest, authentication, crmPhone, companyId, crmFirstName) {

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

    if (contact?.exist) {
        return { created: false, contactId: contact.contactId }
    }

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

    return { created: true, contactId: contact.contactId }
}


