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

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)

    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)
    } catch (error) {
        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('auxTicketStatus: ', auxTicketStatus, ' | auxTicketId: ', auxTicketId)

    return { auxTicketId, auxTicketStatus }

}

module.exports = lookupCrmTicket


