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

async function processBbpsEnquirePayment(body) {
  console.log("BBPS Enquire Payment 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;
  }

  if (!body.validationid) {
    const err = new Error("validationid is required");
    err.statusCode = 400;
    throw err;
  }

  /* =====================================================
     2. BUILD PAYLOAD (BUS STYLE)
     ===================================================== */
  const mercid = process.env.BD_MERCHANT_ID;
  if (!mercid) throw new Error("BD_MERCHANT_ID not configured");

  const payload = { mercid, refund_details: "true" };
  if (body.orderid) payload.orderid = String(body.orderid).trim();
  if (body.transactionid) payload.transactionid = String(body.transactionid).trim();

  const orderid = payload.orderid;
  console.log("📦 BBPS Enquire payload:", payload);

  /* =====================================================
     3. CALL BILLDESK (SDK)
     ===================================================== */
  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 enquiry response:", billdeskResponse);

  /* =====================================================
     4. CLASSIFY PAYMENT STATUS
     ===================================================== */
  const authStatus = billdeskResponse?.auth_status || null;

  const paymentState =
    authStatus === "0300" ? "SUCCESS" :
    authStatus === "0399" ? "FAILED" :
    "PENDING";

  /* =====================================================
     5. INSERT ENQUIRY AUDIT (ALWAYS)
     ===================================================== */
  await dbConnect.execute(
    `
    INSERT INTO bd_enquire_payment_response
    (
      order_id,
      trans_id,
      transaction_date,
      amount,
      surcharge,
      discount,
      charge_amount,
      bank_id,
      bank_ref_no,
      transaction_error_desc,
      transaction_error_type,
      payment_method,
      payment_category
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `,
    [
      billdeskResponse?.orderid || orderid,
      billdeskResponse?.transactionid || null,
      billdeskResponse?.transaction_date
        ? new Date(billdeskResponse.transaction_date)
        : null,
      billdeskResponse?.amount || null,
      billdeskResponse?.surcharge || null,
      billdeskResponse?.discount || null,
      billdeskResponse?.charge_amount || null,
      billdeskResponse?.bankid || null,
      billdeskResponse?.bank_ref_no || null,
      billdeskResponse?.transaction_error_desc || null,
      billdeskResponse?.transaction_error_type || null,
      billdeskResponse?.payment_method_type || null,
      billdeskResponse?.payment_category || null
    ]
  );

  console.log("🧾 Enquiry audit inserted");

  /* =====================================================
     6. HANDLE FAILED / PENDING (NO RECONCILIATION)
     ===================================================== */
  if (paymentState !== "SUCCESS") {
    return {
      success: false,
      status: paymentState,
      auth_status: authStatus,
      orderid,
      transactionid: billdeskResponse?.transactionid || null,
      message:
        paymentState === "FAILED"
          ? "Payment failed at BillDesk"
          : "Payment pending at BillDesk",
      raw: billdeskResponse
    };
  }

/* =====================================================
   7. PHP-STYLE RECONCILIATION (SUCCESS ONLY)
   ===================================================== */
const amount = Number(billdeskResponse.amount || 0);
const transactionId = billdeskResponse.transactionid;
const now = new Date();

/* 7.1 Update onlinepay status */
await dbConnect.execute(
  `UPDATE onlinepay SET status='Transaction Successful' WHERE utranid=?`,
  [orderid]
);

/* 7.2 Fetch payeeid */
const [payeeRows] = await dbConnect.execute(
  `SELECT payeeid FROM onlinepay WHERE utranid=?`,
  [orderid]
);

if (!payeeRows.length) {
  throw new Error(`No payeeid found for utranid ${orderid}`);
}

const uid = String(payeeRows[0].payeeid);

/* 7.3 Initialize balance */
let userbal = 0;
let isLoggedInUser = false;

/* 7.4 Logged-in vs Guest check */
if (uid.startsWith("1")) {
  isLoggedInUser = true;

  const [balRows] = await dbConnect.execute(
    `SELECT ubal FROM ulogin WHERE uid=?`,
    [uid]
  );

  userbal = balRows.length ? Number(balRows[0].ubal) : 0;
}

/* 7.5 Calculate new balance */
const newbal = userbal + amount;

/* 7.6 CREDIT ledger entry (ALWAYS) */
await dbConnect.execute(
  `
  INSERT INTO t_account
    (bal, id, treference, tamount_dr, tamount_cr, newbal, datetime)
  VALUES (?, ?, ?, 0, ?, ?, ?)
  `,
  [userbal, uid, transactionId, amount, newbal, now]
);

/* 7.7 Update wallet ONLY for logged-in users */
// if (isLoggedInUser) {
//   await dbConnect.execute(
//     `UPDATE ulogin SET ubal=? WHERE uid=?`,
//     [newbal, uid]
//   );
// }

/* 7.8 Fetch validation ID */
const [valRows] = await dbConnect.execute(
  `
  SELECT serviceref_id
  FROM onlinepay
  WHERE payeeid=?
    AND serviceref_id IS NOT NULL
    AND status='Transaction Successful'
  ORDER BY updated_at DESC
  LIMIT 1
  `,
  [uid]
);

/* 7.9 DEBIT ledger entry (if validationId exists) */
if (valRows.length) {
  const servicerefId = valRows[0].serviceref_id;

  await dbConnect.execute(
    `
    INSERT INTO t_account
      (bal, id, treference, tamount_dr, tamount_cr, newbal, datetime)
    VALUES (?, ?, ?, ?, 0, ?, ?)
    `,
    [newbal, uid, servicerefId, amount, userbal, now]
  );
}

  /* =====================================================
     8. RETURN SUCCESS TO makePayment
     ===================================================== */
  return {
    success: true,
    status: "SUCCESS",
    auth_status: authStatus,
    orderid,
    transactionid: transactionId,
    amount,
    raw: billdeskResponse
  };
}

module.exports = { processBbpsEnquirePayment };