const { getAccessToken } = require('./oauth2')

async function requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data = '', ticketId = '', companyId) {
    let config = {}
 
    console.log('requestConfigHeader ticketId: ', ticketId)
    url = url.replace('crmPhone', crmPhone)
    url = url.replace('ticketId', ticketId)

    if (type == 'api_token') {
        if (requestType.trim().toLowerCase() == 'post') {
            url = `${url}?api_token=${token}`
        }
        else if (requestType.trim().toLowerCase() == 'get') {
            url = `${url}&api_token=${token}`
        }
    }

    let commonConfig = {
        method: requestType,
        url,
        headers: {
            'Content-Type': requestContentType,
        }
    }

    if (data) {
        commonConfig = { ...commonConfig, data }
    }

    if (type === 'basic') {
        const auth = Buffer.from(`${userName}:${passWord}`).toString('base64')
        config = {
            ...commonConfig,
            headers: {
                ...commonConfig.headers,
                'Authorization': `Basic ${auth}`,
            }
        }
    } else if (type === 'bearer') {
        config = {
            ...commonConfig,
            headers: {
                ...commonConfig.headers,
                'Authorization': `Bearer ${token}`,
            }
        }
    } else if (type === 'oauth2') {
        console.log('===============> requestConfigHeader oauth2 companyId: ', companyId)
        const accessToken = await getAccessToken(crmClientId, companyId)
        config = {
            ...commonConfig,
            headers: {
                ...commonConfig.headers,
                'Authorization': `Bearer ${accessToken}`,
            }
        }
    }
    else if (type === 'api_token') {
        config = {
            ...commonConfig,
            headers: {
                ...commonConfig.headers,
            }
        }
    }
    return config
}

module.exports = requestConfigHeader