const billdeskClient = require("../utils/billdeskClient");
const dbConnect = require("../../busapi/configs/dbConnection");
require("dotenv").config();

/**
 * Retrieve BillDesk transaction details
 * Can be retrieved using:
 *  - mercid + orderid
 *  - mercid + transactionid
 */
async function retrieveTransaction(body) {
  console.log("BillDesk retrieveTransaction request received");

  /* =====================================================
     1. BASIC VALIDATION
     ===================================================== */
  if (
    !body ||
    (!body.orderid && !body.transactionid)
  ) {
    const err = new Error(
      "Missing required field: orderid or transactionid"
    );
    err.statusCode = 400;
    throw err;
  }

  /* =====================================================
     2. BUILD PAYLOAD (DOC COMPLIANT)
     ===================================================== */
     const MERCID = process.env.BD_MERCHANT_ID;
     console.log("MERCID:", MERCID);
  const payload = {
    mercid: MERCID,
    refund_details: "true"  
  };

  if (body.orderid) payload.orderid = body.orderid.trim();
  if (body.transactionid) payload.transactionid = body.transactionid.trim();

console.log("📦 Retrieve payload (plaintext):", payload);

    let orderid = body.orderid;

  /* =====================================================
     3. CALL BILLDESK RETRIEVE TRANSACTION API
     (Same encryption + signing as Create Order)
     ===================================================== */
  const clientId = process.env.BD_CLIENT_ID || process.env.BD_MERCHANT_ID_UAT;


  const billdeskResponse = await billdeskClient.callBilldesk({
    orderid,
    path: "transactions/get",
    payload,
    clientId,
    keyId: process.env.BD_KEY_ID,
    encKey: process.env.BD_ENC_KEY,
    sigKey: process.env.BD_SIGN_KEY
  });

console.log("✅ BillDesk retrieve response:", billdeskResponse);

 // 7️⃣ Extract business fields (example)
    const orderId = billdeskResponse.orderid;
    const bd_txn_id = billdeskResponse.transactionid;
    const authStatus = billdeskResponse.auth_status;
    // const amount = finalPayload.amount;

    const status =
        authStatus === "0300" ? "Transaction Successful" :
        authStatus === "0399" ? "Transaction Failed" :
        "Transaction Pending";
        
     // update online pay table
  await dbConnect.query(
      "UPDATE onlinepay SET status = ? WHERE ipgid = ?",
      [status, orderId]
    );
        



  /* =====================================================
     5. RETURN RESPONSE
     ===================================================== */
  return {
    orderid: billdeskResponse.orderid || null,
    transactionid: billdeskResponse.transactionid || null,
    auth_status: billdeskResponse.auth_status || null,
    amount: billdeskResponse.amount || null,
    currency: billdeskResponse.currency || null,
    payment_method_type: billdeskResponse.payment_method_type || null,
    refundInfo: billdeskResponse.refundInfo || [],
    raw: billdeskResponse
  };
}

module.exports = {retrieveTransaction};


