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

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

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

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


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

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

    if (crmInfo) return { exist: true, contactId: crmInfo.contactId, phone: crmPhone }

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

    if (test?.testing){
        let msg = `Tentanto checar se o contato de numero ${crmPhone} existe no crm`
        sendMessageSocket({ companyId, status: 'processing', data: { request: config, msg } }) 
    }

    let { data } = await axios(config) 

    data = flatten(data)

    let auxPhone
    let auxContactId

    for (const prop in data) {

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

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

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

        if (auxPhone && auxContactId) break

    }

    if (!auxPhone && !auxContactId) {
        for (const prop in data) {

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

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

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

            if (auxPhone && auxContactId) break

        }
    }

    if (auxPhone) {

        if (auxPhone && auxContactId) {
            const crm = await CRM.findOne({ companyId, crmBaseURL: new URL(url).hostname })
            await CRM_Contact.create({ companyId, crm, crmBaseURL: new URL(url).hostname, contactId: auxContactId, phone: auxPhone })
        }

        return { exist: true, contactId: auxContactId, phone: crmPhone }
    } 

    return { exit: false }
}

module.exports = lookupContactByPhone


