const flatten = require('flat')
const unflatten = require('flat').unflatten
const axios = require('axios')
const CRM_Contact = require('../models/CRM_Contact')
const { URL } = require('url')
const findProperty = require('./findProperty')
const CRM = require('../models/CRM')
const requestConfigHeader = require('./requestConfigHeader')
const sendMessageSocket = require('./sendMessageSocket')

async function createContact(companyId, rest, authentication, crmPhone, crmFirstName = 'Username', crmLastName = 'Last name', crmEmail = '', test = {}, dynamicBodyRequest = {}) {
    let { request, body, response } = findProperty(rest, 'createContactRecord')

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

    body = flatten(body)

    const mapping = {
        crmFirstName,
        crmLastName,
        crmPhone,
        crmEmail
    }

    for (const prop in body) {
        if (mapping.hasOwnProperty(body[prop])) {
            const variable = mapping[body[prop]]
            if (variable) {
                body[prop] = variable
            } else {
                if (body[prop] == 'crmLastName' && !crmLastName) {
                    body[prop] = 'Username'
                }
                else
                    delete body[prop]
            }
        }
    }

    body = unflatten(body)

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

    //url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId
    let config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, body, '', companyId)

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

    console.log('#####################')
    console.log('CREATE CONTACT PAYLOAD: ', JSON.stringify(config, null, 6))
    console.log('#####################')

    if (dynamicBodyRequest && Object.keys(dynamicBodyRequest) !== 0) {
        config.data = { ...config.data, ...dynamicBodyRequest }
        console.log('#####################')
        console.log('CREATE CONTACT PAYLOAD UPDATED BY DYNAMIC BODY REQUEST: ', JSON.stringify(config, null, 6))
        console.log('#####################')
    }

    let data
    try {
        let { data: _data } = await axios(config)
        data = _data
    } catch (error) {
        if (error.response) {
            console.error('==================> createContact Erro na resposta da API:', {
                status: error.response.status,
                data: error.response.data,
            })
        }
        else if (error.request) {
            console.error('==================> createContact Nenhuma resposta recebida da API:', error.request)
        }
        else {
            console.error('==================> createContact Erro ao configurar a request:', error.message)
        }

        throw error
    }

    // let { data } = await axios(config)

    data = flatten(data)

    let auxContactId

    for (const prop in data) {

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

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


    if (auxContactId && !test?.testing) {
        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: crmPhone })
    }

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

}

module.exports = createContact