// billdeskpg/utils/billdeskClient.js
const axios = require('axios');
const dbConnect = require("../../busapi/configs/dbConnection");
const { processRequest } = require('./apirequestmodule');
const { encryptAndSign, verifyAndDecrypt } = require('./symjose');
const { processResponse } = require('./apiresponsemodule');

async function callBilldesk({ orderid, path, payload, clientId, keyId, encKey, sigKey }) {
    
    console.log("1");
    const base = process.env.BD_BASE_URL;
    const url = base.endsWith('/') ? `${base}${path}` : `${base}/${path}`;
    console.log("🌐 BillDesk URL:", url);
    
    const { headers, body: plaintext } = processRequest(JSON.stringify(payload));
    console.log("🧾 Headers:", headers);
    console.log("📄 Plaintext payload:", plaintext);
  
    // encrypt + sign
    const joseEnvelope = await encryptAndSign(plaintext, clientId, encKey, sigKey, keyId);
    
    // insert order id and encrypted payload in db
    const query = `
        INSERT INTO billdesk_order_logs (order_id, encoded_request)
        VALUES (?, ?)
        `;
    //const [result] = await dbConnect.query(query, [orderid, joseEnvelope]);
    //console.log(`Order inserted with ID: ${result.insertId}`);
    console.log("3:", url);
    
    // calling billdesk api for creating order
    const resp = await axios.post(url, joseEnvelope, {
        headers,
        timeout: 30000,
        validateStatus: () => true
    });
    // console.log("encodedResponse:", resp);
        console.log("encodedResponse:", resp.data);
    
    // saving encoded responses in db
    const query1 = `
    UPDATE billdesk_order_logs
    SET encoded_response = ?,
        updated_at = CURRENT_TIMESTAMP
    WHERE id = ?
    `;

    //await dbConnect.query(query1, [resp.data, result.insertId]);
    
    console.log("📡 HTTP status:", resp.status);
    console.log("4");
    
    if (resp.status !== 200) {
        let detail = resp.data;
        if (typeof resp.data === 'string' && resp.data.includes('.')) {
            try {
                const decryptedErr = await verifyAndDecrypt(resp.data, encKey, keyId, sigKey, keyId);
                detail = JSON.parse(decryptedErr);
            } catch (e) {
            // keep raw
            }
        }
        console.log("5");
        const err = new Error('BillDesk API call failed');
        err.status = resp.status;
        err.detail = detail;
        throw err;
    }
    console.log("6");
    const decrypted = await verifyAndDecrypt(resp.data, encKey, keyId, sigKey, keyId);
    const parsed = processResponse(decrypted);
    return parsed;
}

module.exports = { callBilldesk };
