const axios = require('axios');
const https = require('https');
const Log = require('./log');
const Info = require('./info');
const db = require('../dbconn');
var Whatsapp = function (obj) { };

Whatsapp.sendAutoReply = function (data) {
    return new Promise(async (resolve, reject) => {
        try {
            if (!data || data.length === 0) {
                Log.whatsappErrorLog('No data provided for sending auto-reply.');
                reject({ status: false, message: 'No data provided for sending auto-reply.' });
            }
            if (!data.wp_api) {
                Log.whatsappErrorLog('Whatsapp API is required for sending auto-reply.');
                reject({ status: false, message: 'Whatsapp API is required for sending auto-reply.' });
            }
            if (!data.mobile_no) {
                Log.whatsappErrorLog('Mobile No is required for sending auto-reply.');
                reject({ status: false, message: 'Mobile No is required for sending auto-reply.' });
            }

            Log.whatsappErrorLog({ msg: `Sending Whatsapp process started on ticket id ${data.ticket_id}, conversation id ${data.conversation_id}, and mobile no ${data.mobile_no}` });

            const escapedUrl = curlEscape(data.conversation);
            const apiUrl = data.wp_api
                .replace('{0}', data.mobile_no)
                .replace('{1}', escapedUrl);

            const agent = new https.Agent({
                rejectUnauthorized: false,
            });

            const axiosConfig = {
                httpsAgent: agent,
                headers: data.wp_api_headers || {}, 
            };

            let response;
            if (data.method === 'POST') {
                axiosConfig.data = data.wp_api_body || {}; 
                response = await axios.post(apiUrl, axiosConfig.data, axiosConfig);
            } else {
                const params = new URLSearchParams(data.wp_api_body || {}).toString();
                const urlWithParams = `${apiUrl}?${params}`;
                response = await axios.get(urlWithParams, axiosConfig);
            }

            if (response.data.status === true) {
                let updArr = {
                    'whatsapp_status': 'Send'
                };
                let whArr = {
                    'conversation_id': data.conversation_id
                };
                let mstTblName = `tms_conversation_master_${data.queue_id}`;
                db.updateData(`${mstTblName}`, updArr, whArr)
                    .then(function (response) {
                        Log.whatsappErrorLog({ msg: `${JSON.stringify(response)}` });
                        if (response.status === true) {
                            return { status: true };
                        } else {
                            Log.whatsappErrorLog({ error: response.err });
                            return { status: false, data: null, err: response.err };
                        }
                    })
                    .catch(function (error) {
                        Log.whatsappErrorLog({ error: error });
                        return { status: false, data: null, err: error };
                    });

                let logArr = {
                    'ticket_id': data.ticket_id,
                    'conversation_id': data.conversation_id,
                    'mobile_no': data.mobile_no,
                    'response': JSON.stringify(response.data),
                };
                let logTblName = `whatsapp_api_log_${data.queue_id}`;
                db.insertData(`${logTblName}`, logArr)
                    .then(function (response) {
                        Log.whatsappErrorLog({ msg: `${JSON.stringify(response)}` });
                        if (response.status === true) {
                            return { status: true };
                        } else {
                            Log.whatsappErrorLog({ error: response.err });
                            return { status: false, data: null, err: response.err };
                        }
                    })
                    .catch(function (error) {
                        Log.whatsappErrorLog({ error: error });
                        return { status: false, data: null, err: error };
                    });
            } else {
                Log.whatsappErrorLog({ msg: `${response.data}` });
                console.log({ msg: `Error while sending Whatsapp for ticket id ${data.ticket_id} and conversation id ${data.conversation_id}: ${response.data}` });
                resolve({ status: true, message: `${response.data}` });
            }

        } catch (err) {
            Log.whatsappErrorLog({ err: err });
            reject({ status: false, data: null, err: err });
        }
    });
};

function curlEscape(str) {
    return encodeURIComponent(str)
        .replace(/[!'()*]/g, function(c) {
            return '%' + c.charCodeAt(0).toString(16);
        })
        .replace(/~/g, '%7E');
}

module.exports = Whatsapp;