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

Sms.sendAutoReply = function (data) {
  

    return new Promise(async (resolve, reject) => {
        try {
            if (!data || Object.keys(data).length === 0) {
                const msg = 'No data provided for sending auto-reply.';
                Log.smsErrorLog(msg);
                return reject({ status: false, message: msg });
            }

            const method = data.sms_api_method ? data.sms_api_method.toUpperCase() : null;

            if (!method || !['GET', 'POST'].includes(method)) {
                const msg = 'Invalid or missing SMS API method.';
                Log.smsErrorLog(msg);
                return reject({ status: false, message: msg });
            }

            if (!data.sms_api) {
                const msg = 'SMS API is required for sending auto-reply.';
                Log.smsErrorLog(msg);
                return reject({ status: false, message: msg });
            }

            if (!data.mobile_no) {
                const msg = 'Mobile No is required for sending auto-reply.';
                Log.smsErrorLog(msg);
                return reject({ status: false, message: msg });
            }

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

            const apiUrl = data.sms_api
                .replace('{0}', data.mobile_no)
                .replace('{1}', encodeURIComponent(data.conversation || ''));

            let headers = {};
            let paramsOrBody = {};

            try {
                if (data.sms_api_headers) {
                    // Clean and parse escaped header string
                    const cleanedHeaders = data.sms_api_headers
                        .replace(/\\"/g, '"')        // Replace escaped quotes
                        .replace(/^"|"$/g, '');      // Remove wrapping quotes                       
                    headers = JSON.parse(cleanedHeaders);
                }
                if (data.sms_api_body) {
                    // Clean and parse escaped body string
                    const cleanedBody = data.sms_api_body
                        .replace(/\\"/g, '"')
                        .replace(/^"|"$/g, '');
                    paramsOrBody = JSON.parse(cleanedBody);

                    // Replace placeholders in the body with actual values
                    for (const key in paramsOrBody) {
                        if (typeof paramsOrBody[key] === 'string') {
                            paramsOrBody[key] = paramsOrBody[key]
                                .replace('{0}', data.mobile_no)
                                .replace('{1}', encodeURIComponent(data.conversation || ''));
                        }
                    }
                }
            } catch (parseErr) {
                Log.smsErrorLog({ msg: 'Failed to parse headers or body', err: parseErr });
                return reject({ status: false, message: 'Invalid JSON format in headers or body.', err: parseErr });
            }

            let response;
            if (method === 'GET') {
                response = await axios.get(apiUrl, { headers, params: paramsOrBody });
            } else if (method === 'POST') {
                response = await axios.post(apiUrl, {  paramsOrBody}, { headers });
            }

            
            const pattern = /SimpleMessageSuccessResponse \[status=(\w+), mobile=(\d+), invalidMobile=, transactionId=(\d+), statusCode=(\d+), reason=(\w+), msgId=\]/;

            if (typeof response.data === 'string' && response.data.match(pattern)) {
                var match = response.data.match(pattern);
                Log.smsErrorLog({ msg: `${JSON.stringify(match)}` });
            } else if (response.data.status == "success") {
                var match = true;
                Log.smsErrorLog({ msg: `${match}` });
            }else  if (response.data.includes("Sent")) {
                var match = true;
                Log.smsErrorLog({ msg: `${match}` });
            }
            console.log("match", response.data);

            if (match) {
                if (typeof match !== 'boolean') {
                    const dataObject = {
                        status: match[1],
                        mobile: match[2],
                        transactionId: match[3],
                        statusCode: match[4],
                        reason: match[5],
                    };
                } else {
                    var dataObject = {
                        status: "success",
                    }
                }

                if (dataObject.status === "success") {
                    const updArr = { 'sms_status': 'Send' };
                    const whArr = { 'conversation_id': data.conversation_id };
                    const mstTblName = `tms_conversation_master_${data.queue_id}`;
                    await db.updateData(mstTblName, updArr, whArr);

                    const logArr = {
                        'ticket_id': data.ticket_id,
                        'conversation_id': data.conversation_id,
                        'mobile_no': data.mobile_no,
                        'response': response.data,
                    };
                    const logTblName = `sms_api_log_${data.queue_id}`;
                    await db.insertData(logTblName, logArr);

                    return resolve({ status: true });
                } else {
                    Log.smsErrorLog({ msg: response.data });
                    return resolve({ status: false, message: response.data });
                }
            } else {
                Log.smsErrorLog({ msg: response.data });
                return resolve({ status: false, message: response.data });
            }

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

 Sms.callOtherApiForToken = async () => {
    try {
       let data = qs.stringify({
          'client_id': 'IFFCO.UAT',
          'client_secret': 'wFUHFh2H',
          'grant_type': 'client_credentials'
       });
 
       let config = {
          method: 'post',
          maxBodyLength: Infinity,
          url: 'https://identity-uat.kprocentral.com/connect/token',
          headers: {
             'Content-Type': 'application/x-www-form-urlencoded',
             'Cookie': '.AspNetCore.Culture=c%3Den-GB%7Cuic%3Den-GB; dde3bc95fbca64e8dcd331d63640ffdc=79c4d5024554ff0c1940ba15b0638d7f'
          },
          data: data
       };
 
       const response = await axios.request(config);
       return { status: true, token: response.data.access_token };
    } catch (error) {
       console.error("Error in callOtherApiForToken:", error);
       return { status: false, error: error.message };
    }
 };
// Sms.sendAutoReply = function (data) {
//     console.log(data,"data in sms.js");
//     return new Promise(async (resolve, reject) => {
//         try {
//             if (!data || data.length === 0) {
//                 Log.smsErrorLog('No data provided for sending auto-reply.');
//                 reject({ status: false, message: 'No data provided for sending auto-reply.' });
//             }
//             if (!data.sms_api_method || !['GET', 'POST'].includes(data.sms_api_method.toUpperCase())) {
//                 Log.smsErrorLog('Invalid or missing SMS API method.');
//                 reject({ status: false, message: 'Invalid or missing SMS API method.' });
//             }
//             if (!data.sms_api) {
//                 Log.smsErrorLog('SMS API is required for sending auto-reply.');
//                 reject({ status: false, message: 'SMS API is required for sending auto-reply.' });
//             }
//             if (!data.mobile_no) {
//                 Log.smsErrorLog('Mobile No is required for sending auto-reply.');
//                 reject({ status: false, message: 'Mobile No is required for sending auto-reply.' });
//             }

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

//             const apiUrl = data.sms_api
//                 .replace('{0}', data.mobile_no)
//                 .replace('{1}', encodeURIComponent(data.conversation));

//             let response;
//             if (data.sms_api_method.toUpperCase() === 'GET') {
//                 const headers = data.sms_api_headers ? JSON.parse(data.sms_api_headers) : {};
//                 const params = data.sms_api_body ? JSON.parse(data.sms_api_body) : {};
//                 response = await axios.get(apiUrl, { headers, params });                
//             } else if (data.sms_api_method.toUpperCase() === 'POST') {
//                 const headers = data.sms_api_headers ? JSON.parse(data.sms_api_headers) : {};
//                 const body = data.sms_api_body ? JSON.parse(data.sms_api_body) : {};
//                 response = await axios.post(apiUrl, body, { headers });
//             }

//             const pattern = /SimpleMessageSuccessResponse \[status=(\w+), mobile=(\d+), invalidMobile=, transactionId=(\d+), statusCode=(\d+), reason=(\w+), msgId=\]/;

//             const match = response.data.match(pattern);
//             if (match) {
//                 const dataObject = {
//                     status: match[1],
//                     mobile: match[2],
//                     transactionId: match[3],
//                     statusCode: match[4],
//                     reason: match[5],
//                 };

//                 if (dataObject.status === "success") {
//                     let updArr = { 'sms_status': 'Send' };
//                     let whArr = { 'conversation_id': data.conversation_id };
//                     let mstTblName = `tms_conversation_master_${data.queue_id}`;
//                     await db.updateData(mstTblName, updArr, whArr);

//                     let logArr = {
//                         'ticket_id': data.ticket_id,
//                         'conversation_id': data.conversation_id,
//                         'mobile_no': data.mobile_no,
//                         'response': response.data,
//                     };
//                     let logTblName = `sms_api_log_${data.queue_id}`;
//                     await db.insertData(logTblName, logArr);

//                     resolve({ status: true });
//                 } else {
//                     Log.smsErrorLog({ msg: `${response.data}` });
//                     resolve({ status: false, message: `${response.data}` });
//                 }
//             } else {
//                 Log.smsErrorLog({ msg: `${response.data}` });
//                 resolve({ status: false, message: `${response.data}` });
//             }

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

module.exports = Sms;
