const axios = require('axios')
const flatten = require('flat')
const CustomError = require('../errors')
const CRM_Contact = require('../models/CRM_Contact')
const CRM = require('../models/CRM')

const { URL } = require('url')
const { getAccessToken } = require('./oauth2')
const findProperty = require('./findProperty')
const requestConfigHeader = require('./requestConfigHeader')
const sendMessageSocket = require('./sendMessageSocket')
const CRM_Ticket = require('../models/CRM_Ticket')

const getHubspotPipelines = require('./getHubspotPipelines')
const { pipeline } = require('stream')
const findTicketOpenHubspotByContact = require('./findTicketOpenHubspotByContact')
const lookupContactByPhone = require('./lookupCRMContactByPhone')


async function lookupCrmTicket(rest, authentication, crmPhone, companyId, test = {}, ticketId) {

    let { request, body, response } = findProperty(rest, 'lookupTicket')

    let { requestContentType, requestEncoding, requestType, responseType, url } = request


    const { type, userName, passWord, token, crmClientId } = authentication

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

    if (test?.testing) {
        let msg = `Tentanto checar o status do ticket para o numer ${crmPhone} no crm`
        sendMessageSocket({ companyId, status: 'processing', data: { request: config, msg } })
    }

    let resp

    try {
        resp = await axios(config)

        console.log(`====> CompanyId: ${companyId} Request config para consultar status do ticket\n: `, JSON.stringify(config, null, 6))
        console.log(`====> CompanyId: ${companyId} Response consultar status do ticket\n: `, JSON.stringify(resp.data, null, 6))

    } catch (error) {

        if (error.response) {
            console.error('==================> lookupCrmTicket Erro na resposta da API:', {
                status: error.response.status,
                data: error.response.data,
            })
        }
        else if (error.request) {
            console.error('==================> lookupCrmTicket Nenhuma resposta recebida da API:', error?.request)
        }
        else {
            console.error('==================> lookupCrmTicket Erro ao configurar a request:', error?.message)
        }

        if (error?.response?.status == 404)
            return { error: 404 }
    }

    let { data } = resp

    data = flatten(data)

    let auxTicketStatus
    let auxTicketId

    for (const prop in data) {

        const _prop = prop.replace(/^\d+\./, '').replace(/(?:^|\.)\d+\b/g, '')

        if (_prop == response?.status?.trim()) {
            auxTicketStatus = data[prop].replace('+', '')
        }

        if (_prop == response?.id?.trim()) {
            auxTicketId = data[prop]
        }

        if (auxTicketStatus && auxTicketId) break

    }

    if (!auxTicketStatus && !auxTicketId) {
        for (const prop in data) {

            let _prop = prop.replace(/\.(\d+)(\.|$)/g, '[$1]$2')

            if (_prop == response?.status?.trim()) {
                auxTicketStatus = data[prop].replace('+', '')
            }

            if (_prop == response?.id?.trim()) {
                auxTicketId = data[prop]
            }

            if (auxTicketStatus && auxTicketId) break

        }
    }

    console.log(`[${new Date()}] auxTicketStatus: ${auxTicketStatus} | auxTicketId: ${auxTicketId}`)

    if (url.includes('api.hubapi.com')) {
 
        const contact = await lookupContactByPhone(rest, authentication, crmPhone, companyId)

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

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

        }
 
        return { auxTicketId, auxTicketStatus }
     
    } 

    return { auxTicketId, auxTicketStatus }

}

module.exports = lookupCrmTicket


