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 { request, body, response } = findProperty(rest, 'createTicketRecord')

    const { requestContentType, requestEncoding, requestType, responseType, url } = request
 
 
    body = flatten(body)

    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)

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

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

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

    let { data } = await axios(config)

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

        sendEventTicketCreatedToSocket({ companyId, extension: crmAgent, ticketUrl: `https://app.hubspot.com/contacts/44357029/ticket/${auxTicketId}` })

    }

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

}

module.exports = createTicket