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


async function redirectContactLinkCRM(companyId, crmPhone, crmAgent, crmFirstName = 'Username') {

    const crmFiles = await loadCRM(companyId)

    const crmContactIds = []

    for (const crmConfig of crmFiles) {

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

        // Send the edited contact/lead link url to hitphone to open on another browser tab
        let redirectLink = findProperty(rest, 'redirectLink')

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

            const { contactId, created } = contact

            const url = redirectLink?.request?.url?.replace(/crmContactId/g, contactId)

            console.log('===============> Edit url rediret sended to hitphone: ', url)

            console.log('new URL(url).hostname: ', new URL(url).hostname)

            crmContactIds.push({ crm: new URL(url).hostname, contactId, created })

            // sendEventTicketCreatedToSocket({ companyId, extension: crmAgent, ticketUrl: url })    
        }
        //  

    }

    return crmContactIds

}

module.exports = redirectContactLinkCRM


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 }
}

 
