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 getHubspotTicketStatus = require('./getHubspotTicketStatus')
const getHubspotTicket = require('./getHubspotTicket')
const getHubspotPipelines = require('./getHubspotPipelines')
const mongoose = require('mongoose')
const getHubspotTicketStatusByContact = require('./getHubspotTicketStatusByContact')
const findTicketOpenHubspotByContact = require('./findTicketOpenHubspotByContact')

async function ticketCRM(companyId, crmPhone, crmAgent = "0000", crmFirstName = 'Username') {

    const crmFiles = await loadCRM(companyId)

    // const crmContactIds = []
    const crmTicketLinks = []

    for (const crmConfig of crmFiles) {

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

        // Send the ticket url link to hitphone to open on another browser tab
        let obj = findProperty(rest, 'lookupTicket')

        let ticket_id = ''
        let isCreated = false

        if (obj) {

            const { crmAccountId } = authentication

            console.log("------------> ticketCRM crmAccountId: ",crmAccountId)

            let { url } = obj.request
            let contact = await _lookupContact(rest, authentication, crmPhone, companyId, crmFirstName, url)

            const crm = await CRM.findOne({
                companyId, crmBaseURL: new URL(url.trim()).hostname
            })

            const obj_contact = await CRM_Contact.findOne({ companyId, crmBaseURL: new URL(url).hostname, phone: crmPhone })

            const obj_ticket = await CRM_Ticket.findOne(
                { companyId, crm, contact: obj_contact }
            ).select('ticketId')

            if (obj_ticket) {

                const { ticketId } = obj_ticket

                if (ticketId) {
                    ticket_id = ticketId
                }

                const obj_ticket_status = await lookupCRMTicket(
                    rest,
                    authentication,
                    crmPhone,
                    companyId,
                    test = { testing: false },
                    obj_ticket.ticketId
                )

                if (obj_ticket_status)
                    console.log("obj_ticket_status: ", JSON.stringify(obj_ticket_status, null, 6))

                if (obj_ticket_status) {
                    const { auxTicketStatus, error } = obj_ticket_status

                    // refactor this for production. For now only working with hubspot where status new is equal 1
                    if ((auxTicketStatus && auxTicketStatus != '1') || (error && error == 404)) {

                        await CRM_Ticket.deleteMany({ contact: obj_contact })

                        if (url.includes("hubapi")) {

                            const result = await findTicketOpenHubspot(authentication, contact)

                            if (result) {

                                const { ticketId } = result

                                await sincTicket(authentication, contact, companyId, crm, obj_contact, ticketId)

                                ticket_id = ticketId
                                isCreated = false

                                crmTicketLinks.push({
                                    ticketId: `https://app.hubspot.com/contacts/${crmAccountId}/ticket/${ticket_id}`,
                                    created: isCreated,
                                })

                                continue
                            }


                        }

                        const { ticketUrl, ticketId } = await _createTicket(rest, crmPhone, companyId, authentication, crmFirstName, contact, crmAgent)

                        ticket_id = ticketId
                        isCreated = true
                        // crmTicketLinks.push({ ticketUrl, ticketId })

                    }
                }

            }
            else {


                if (url.includes("hubapi")) {

                    console.log(`[${new Date()}] ****** IS HUBSPOT CRM LETS TRY FINDING AN OPEN TICKET TO THE CONTACT****** `)

                    const result = await findTicketOpenHubspot(authentication, contact)

                    if (result) {
                        const { ticketId } = result

                        // Closed é a label padrão do ticket no hubspot
                        await sincTicket(authentication, contact, companyId, crm, obj_contact, ticketId)

                        ticket_id = ticketId
                        isCreated = false

                        crmTicketLinks.push({
                            ticketId: `https://app.hubspot.com/contacts/${crmAccountId}/ticket/${ticket_id}`,
                            created: isCreated,
                        })

                        continue
                    }
                }

                console.log(`[${new Date()}] ****** CREATE TICKET ****** `)


                const { ticketUrl, ticketId } = await _createTicket(rest, crmPhone, companyId, authentication, crmFirstName, contact, crmAgent)
                ticket_id = ticketId
                isCreated = true
            }

            crmTicketLinks.push({
                ticketId: `https://app.hubspot.com/contacts/${crmAccountId}/ticket/${ticket_id}`,
                created: isCreated,
            })


        }
        // 

    }
    return crmTicketLinks

}

module.exports = ticketCRM


async function sincTicket(authentication, contact, companyId, crm, obj_contact, ticketId) {
    const { token } = authentication
    const data = await getHubspotTicket(token, contact.contactId)

    if (data && data?.results.length > 0) {

        for (const ticket of data.results) {

            const _ticket = await CRM_Ticket.findOne(
                { companyId, crm, ticketId: ticket.id }
            )

            if (_ticket) {
                await _ticket.deleteOne()
            }

        }

    }

    await CRM_Ticket.create({
        companyId,
        contact: obj_contact,
        ticketId: ticketId,
        crm
    })

}

async function findTicketOpenHubspot(authentication, contact) {

    const ticket = await findTicketOpenHubspotByContact(authentication, contact)
    console.log('=========> OPEN TICKET 2: ', JSON.stringify(ticket, null, 6))

    if (ticket && Object.keys(ticket).length != 0) {
        console.log('**** TICKET ESTA ABERTO 2 ****')
        return { ticketId: ticket.id, auxTicketStatus: 1 }
    }

}

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

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

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

    if (!contact?.exist) {
        const contacts = await CRM_Contact.find({ companyId, crmBaseURL: new URL(url).hostname, phone: crmPhone })

        if (contacts) {
            for (const contact of contacts) {

                await CRM_Ticket.deleteMany({ companyId, contact: contact })

                await contact.deleteOne()
            }
        }

        contact = await createContact(companyId, rest, authentication, crmPhone, crmFirstName)
    }

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

async function _createTicket(rest, crmPhone, companyId, authentication, crmFirstName, contact, crmAgent) {
    let obj = findProperty(rest, 'createTicketRecord')

    let ticket_url = ''
    let ticket_id = ''

    if (obj) {
        let { request, response } = obj

        if (request) {
            msg = `Tentando criar ticket para o contato ${crmPhone}`
            //     return { exist: true, ticketId: auxTicketId, phone: crmPhone, ticketUrl } 

            //  return { exist: true, ticketId: auxTicketId, phone: crmPhone, ticketUrl }
            const { ticketUrl, ticketId, } = await createTicket(companyId,
                rest,
                authentication,
                crmPhone,
                crmFirstName = 'Username',
                crmLastName = '',
                crmEmail = '',
                test = { testing: false },
                crmContactId = contact.contactId,
                crmAgent
            )

            ticket_id = ticketId
            ticket_url = ticketUrl
        }
    }
    return { crmFirstName, ticketUrl: ticket_url, ticketId: ticket_id }
}

