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


async function createTicket(companyId, rest, authentication, crmPhone, crmFirstName = 'Username', crmLastName = 'Last name', crmEmail = '', test = {}, crmContactId, crmAgent) {

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

    console.log('==============> crmContactId: ', crmContactId)

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

    console.log('========> body1: ', JSON.stringify(body, null, 6))

    body = flatten(body)

    console.log('========> body2: ', JSON.stringify(body, null, 6))

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

    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)

    console.log('========> body3: ', JSON.stringify(body, null, 6))

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

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

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

    // console.log('===============> createTicket: ', JSON.stringify(config, null, 6))





    let resp

    try {

        console.log("========> createTicket PAYLOAD: ", JSON.stringify(config, null, 6))

        resp = await axios(config)

    } catch (error) {

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

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

    let { data } = resp

    data = flatten(data)

    let auxTicketId

    for (const prop in data) {

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

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

    if (auxTicketId && !test?.testing) {
        const contact = await CRM_Contact.findOne({ companyId, crmBaseURL: new URL(url).hostname, phone: crmPhone })
        const crm = await CRM.findOne({ companyId, crmBaseURL: new URL(url).hostname })

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

        // ticketUrl = `https://app.hubspot.com/contacts/23636141/ticket/${auxTicketId}`
        ticketUrl = `https://app.hubspot.com/contacts/${crmAccountId}/ticket/${auxTicketId}`

        sendEventTicketCreatedToSocket({ companyId, extension: crmAgent, ticketUrl: ticketUrl })

    }

    return { exist: true, ticketId: auxTicketId, phone: crmPhone, ticketUrl }

}

module.exports = createTicket
