const { dateTime, secondsFormat, getPastDateTimeFromSeconds, currentYearMonthDay } = require('./dateTime')
const requestConfigHeader = require('./requestConfigHeader')
const flatten = require('flat')
const unflatten = require('flat').unflatten
const axios = require('axios')
const path = require('path')
const convertToIntegerIfNumber = require('./convertToIntegerIfNumber')
const sendMessageSocket = require('./sendMessageSocket')
                              // request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, rest,      companyId
async function journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, test = {}, companyId='') {
    const { requestContentType, requestEncoding, requestType, responseType, url } = request

    console.log('----------> crmCallDuration: ', crmCallDuration)
    console.log('----------> url: ', url)

    body = flatten(body)

    let ignore = []

    for (let key in body) {

        // console.log('----------> key: ', key)

        const k = Object.keys(body).find(k => {
            if (!ignore.includes(k) && k.includes('._prop') && k.replace('._prop', '._type') ==
                key.replace('._prop', '._type')) {
                ignore.push(key)
                return true
            }
        }
        )

        if (k) {
            const type = body[k.replace('._prop', '._type')]
            const format = body[k.replace('._prop', '._format')]

            const newKey = k.replace('._prop', '').replace('._type', '').replace('._format', '')

            if (body[key] == 'crmCallDuration') {
                switch (format) {
                    case 'hh:mm':
                        body[newKey] = secondsFormat(crmCallDuration, 'hh:mm')
                        break
                    case 'milliseconds':
                        body[newKey] = secondsFormat(crmCallDuration, 'milliseconds')
                        break
                    case 'seconds':
                        body[newKey] = secondsFormat(crmCallDuration, 'seconds')
                        break
                }
            }
            else if (body[key] == 'crmCallDateTime') {
                switch (format) {
                    case 'ISO8601':
                        body[newKey] = crmCallDuration ? getPastDateTimeFromSeconds(dateTime(), crmCallDuration) : dateTime()
                        break
                }
            }
            else if (body[key] == 'crmContactId') {
                body[newKey] = contact.contactId
            }
            else if (body[key] == 'crmAgent') {
                body[newKey] = crmAgent
            }
            else if (body[key] == 'crmPhone') {
                body[newKey] = crmPhone
            }

            const property = body[newKey] ? body[newKey] : body[key]

            switch (type) {
                case 'number':
                    body[newKey] = convertToIntegerIfNumber(property)
                    break
                case 'string':
                    body[newKey] = `${property}`
                    break
                case 'boolean':
                    body[newKey] = Boolean(property)
                    break
            }
            continue
        }

        switch (body[key]) {
            case 'crmPhone':
                body[key] = crmPhone
                break
            case 'crmContactId':
                body[key] = contact.contactId
                break
            case 'crmAgent':
                body[key] = crmAgent
                break
            case 'crmCallDuration':
                body[key] = crmCallDuration
                break
            case 'YYYY-MM-DD':
                body[key] = currentYearMonthDay()
                break 
        }

        // switch (true){
        //     case body[key].includes('chatLink'):
        //         console.log('----------> includes chatlink: ', body[key])
        //         body[key] = body[key].replace('chatLink', 'https://el-vendas.omnihit.app.br/app/accounts/15/conversations/81')
        //     break
        // }

        // console.log('----------> body[key]: ', body[key])



    }



    const data = unflatten(body)

    const { type, userName, passWord, token, crmClientId } = 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, data,                 '', companyId)

    if (test?.testing && test?.companyId && test?.msg) {
        sendMessageSocket({ companyId: test.companyId, status: 'processing', data: { request: config, msg: test.msg } })
    }

    console.log('#####################')
    console.log('CONFIG CALL JOURNALING: ', JSON.stringify(config, null, 6))
    console.log('#####################')

    try {
        const res = await axios(config)
    } catch (error) {
        // console.log(`CALL JOURNALING ERROR: `, error)

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


}

module.exports = journalingRequest