const axios = require('axios')

async function getContactIdChatwoot(url, token, phone) {

    const config = {
        method: 'get',
        url: `${url}/api/v1/accounts/15/contacts/search?q=${phone}`,
        headers: {
            'api_access_token': token
        }
    }

    try {
        const { data } = await axios(config)

        return data.payload[0].id
    } catch (error) {
        console.error(error)
    }
}

async function createConversation(data, omnihitConfig) {

    const { url, accountId, token } = omnihitConfig

    const config = {
        method: 'post',
        url: `${url}/api/v1/accounts/${accountId}/conversations`,
        headers: {
            'api_access_token': token,
            'Content-Type': 'application/json'
        },
        data: data
    }


    try {
        const { data } = await axios(config)
        return data.id
    } catch (error) {
        console.error(error)
    }
}

async function toggleConversationStatus(url, accountId, token, ticketId, payload) {

    const config = {
        method: 'post',
        url: `${url}/api/v1/accounts/${accountId}/conversations/${ticketId}/toggle_status`,
        headers: {
            'api_access_token': token,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(payload)
    }

    try {
        const response = await axios(config)
        console.log(JSON.stringify(response.data))
    } catch (error) {
        console.error(error)
    }
}

module.exports = {
    getContactIdChatwoot,
    createConversation,
    toggleConversationStatus
}
