// billdeskpg/controllers/billdeskFlightWebResponseController.js

/* =====================================================
  REACT APP URL
  🔹 Change port if your React runs on different port
  ===================================================== */
const REACT_APP_URL = "http://localhost:5173/flight-payment-result";

/* =====================================================
  HELPER: Decode BillDesk JWT response (no verification)
  Same approach as PHP explode('.', $jwt)
  ===================================================== */
function decodeJWTResponse(token) {
  const parts = token.split(".");
  if (parts.length < 2) throw new Error("Invalid JWT format from BillDesk");
  const payload = Buffer.from(parts[1], "base64url").toString("utf8");
  return JSON.parse(payload);
}

exports.flightWebResponse = async (req, res) => {
  try {
    console.log("Flight WebSDK Response received from BillDesk");

    /* =====================================================
      1. CHECK POST BODY
      ===================================================== */
    if (!req.body || !req.body.transaction_response) {
      return res.redirect(`${REACT_APP_URL}?success=false&message=Invalid+Access`);
    }

    const jwt = req.body.transaction_response;

    /* =====================================================
      2. DECODE JWT (same as PHP)
      ===================================================== */
    let payload;
    try {
      payload = decodeJWTResponse(jwt);
    } catch (e) {
      console.error("JWT decode failed:", e.message);
      return res.redirect(`${REACT_APP_URL}?success=false&message=Invalid+transaction+response`);
    }

    if (!payload) {
      return res.redirect(`${REACT_APP_URL}?success=false&message=Empty+payload`);
    }

    /* =====================================================
      3. EXTRACT BILLDESK RESPONSE (same as PHP)
      ===================================================== */
    const bdorderid      = payload.bdorderid              ?? null;
    const transactionid  = payload.transactionid          ?? null;
    const authStatus     = payload.auth_status            ?? null; // 0300 = success
    const statusMessage  = payload.transaction_error_desc ?? "Unknown status";
    const amount         = payload.amount                 ?? null;
    const additionalInfo = payload.additional_info        ?? {};

    const userId          = additionalInfo.additional_info1 ?? null;
    const passengerName   = additionalInfo.additional_info2 ?? null;
    const locatorCode     = additionalInfo.additional_info3 ?? null;
    const airLocatorCode  = additionalInfo.additional_info4 ?? null;
    const providerLocator = additionalInfo.additional_info5 ?? null;

    console.log("Flight WebSDK Response => bdorderid:", bdorderid, "| transactionid:", transactionid, "| authStatus:", authStatus);

    /* =====================================================
      4. DETERMINE PAYMENT STATUS
      ===================================================== */
    const isSuccess = authStatus === "0300";

    /* =====================================================
      5. REDIRECT TO REACT APP WITH QUERY PARAMS
      ===================================================== */
    const queryParams = new URLSearchParams({
      success:                isSuccess,
      bdorderid:              bdorderid       || "",
      transactionid:          transactionid   || "",
      authStatus:             authStatus      || "",
      statusMessage:          statusMessage   || "",
      amount:                 amount          || "",
      user_id:                userId          || "",
      passenger_name:         passengerName   || "",
      universal_locator_code: locatorCode     || "",
      air_locator_code:       airLocatorCode  || "",
      provider_locator_code:  providerLocator || "",
    }).toString();

    return res.redirect(`${REACT_APP_URL}?${queryParams}`);

  } catch (err) {
    console.error("Flight WebSDK Response Controller error:", err && err.stack || err);
    return res.redirect(`${REACT_APP_URL}?success=false&message=Internal+server+error`);
  }
};



// billdeskpg/controllers/billdeskFlightWebResponseController.js

// function decodeJWTResponse(token) {
//   const parts = token.split(".");
//   if (parts.length < 2) throw new Error("Invalid JWT format from BillDesk");
//   const payload = Buffer.from(parts[1], "base64url").toString("utf8");
//   return JSON.parse(payload);
// }

// function renderPage({ isSuccess, bdorderid, transactionid, authStatus, statusMessage, amount, userId, passengerName, locatorCode, airLocatorCode, providerLocator }) {
//   const color   = isSuccess ? "#16a34a" : "#dc2626";
//   const icon    = isSuccess ? "✓" : "✕";
//   const title   = isSuccess ? "Payment Successful" : "Payment Failed";

//   const row = (label, value) => `
//     <div style="display:flex;justify-content:space-between;align-items:center;
//                 padding:13px 24px;border-bottom:1px solid #f0f0f0;gap:16px;">
//       <span style="font-size:13px;color:#888;flex-shrink:0;">${label}</span>
//       <span style="font-size:13px;color:#111;font-family:monospace;text-align:right;word-break:break-all;">${value || "—"}</span>
//     </div>`;

//   return `<!DOCTYPE html>
// <html lang="en">
// <head>
//   <meta charset="UTF-8"/>
//   <meta name="viewport" content="width=device-width,initial-scale=1"/>
//   <title>${title}</title>
//   <style>
//     *{box-sizing:border-box;margin:0;padding:0;}
//     body{font-family:'Segoe UI',sans-serif;background:#f5f5f5;min-height:100vh;padding:40px 16px;}
//     .card{max-width:540px;margin:0 auto;background:#fff;border-radius:16px;
//           box-shadow:0 2px 16px rgba(0,0,0,.10);overflow:hidden;}
//     .banner{background:${color};padding:32px 24px;text-align:center;color:#fff;}
//     .icon{width:64px;height:64px;border-radius:50%;background:rgba(255,255,255,.2);
//           display:flex;align-items:center;justify-content:center;
//           margin:0 auto 16px;font-size:30px;font-weight:700;}
//     h1{font-size:22px;font-weight:700;margin-bottom:6px;}
//     .sub{font-size:14px;opacity:.85;}
//     .footer{padding:20px 24px;text-align:center;}
//     .btn{display:inline-block;margin-top:8px;padding:11px 28px;
//          border-radius:8px;background:${color};color:#fff;
//          font-size:14px;font-weight:600;text-decoration:none;border:none;cursor:pointer;}
//     summary{padding:14px 24px;font-size:12px;color:#aaa;cursor:pointer;
//             border-top:1px solid #f0f0f0;list-style:none;}
//     pre{padding:0 24px 20px;font-size:11px;color:#555;
//         white-space:pre-wrap;word-break:break-all;line-height:1.7;}
//   </style>
// </head>
// <body>
//   <div class="card">

//     <div class="banner">
//       <div class="icon">${icon}</div>
//       <h1>${title}</h1>
//       <p class="sub">${statusMessage || ""}</p>
//     </div>

//     ${row("Auth Status",       authStatus)}
//     ${row("Amount",            amount ? "₹ " + amount : "")}
//     ${row("Transaction ID",    transactionid)}
//     ${row("Order ID",          bdorderid)}
//     ${row("Passenger",         passengerName)}
//     ${row("User ID",           userId)}
//     ${row("Universal Locator", locatorCode)}
//     ${row("Air Locator",       airLocatorCode)}
//     ${row("Provider Locator",  providerLocator)}

//     <details>
//       <summary>Show raw values</summary>
//       <pre>${JSON.stringify({ isSuccess, bdorderid, transactionid, authStatus, statusMessage, amount, userId, passengerName, locatorCode, airLocatorCode, providerLocator }, null, 2)}</pre>
//     </details>

//     <div class="footer">
//       <a class="btn" href="/">Go to Home</a>
//     </div>

//   </div>
// </body>
// </html>`;
// }

// exports.flightWebResponse = async (req, res) => {
//   try {
//     console.log("Flight WebSDK Response received from BillDesk");

//     if (!req.body || !req.body.transaction_response) {
//       return res.send(renderPage({
//         isSuccess: false, statusMessage: "Invalid Access — no transaction_response in POST body",
//       }));
//     }

//     const jwt = req.body.transaction_response;

//     let payload;
//     try {
//       payload = decodeJWTResponse(jwt);
//     } catch (e) {
//       console.error("JWT decode failed:", e.message);
//       return res.send(renderPage({
//         isSuccess: false, statusMessage: "JWT decode failed: " + e.message,
//       }));
//     }

//     if (!payload) {
//       return res.send(renderPage({
//         isSuccess: false, statusMessage: "Empty payload after JWT decode",
//       }));
//     }

//     const bdorderid      = payload.bdorderid              ?? null;
//     const transactionid  = payload.transactionid          ?? null;
//     const authStatus     = payload.auth_status            ?? null;
//     const statusMessage  = payload.transaction_error_desc ?? "Unknown status";
//     const amount         = payload.amount                 ?? null;
//     const additionalInfo = payload.additional_info        ?? {};

//     const userId          = additionalInfo.additional_info1 ?? null;
//     const passengerName   = additionalInfo.additional_info2 ?? null;
//     const locatorCode     = additionalInfo.additional_info3 ?? null;
//     const airLocatorCode  = additionalInfo.additional_info4 ?? null;
//     const providerLocator = additionalInfo.additional_info5 ?? null;

//     const isSuccess = authStatus === "0300";

//     console.log("Flight WebSDK Response => bdorderid:", bdorderid,
//                 "| transactionid:", transactionid, "| authStatus:", authStatus);

//     return res.send(renderPage({
//       isSuccess, bdorderid, transactionid, authStatus,
//       statusMessage, amount, userId, passengerName,
//       locatorCode, airLocatorCode, providerLocator,
//     }));

//   } catch (err) {
//     console.error("Flight WebSDK Response Controller error:", err && err.stack || err);
//     return res.send(renderPage({
//       isSuccess: false,
//       statusMessage: "Internal server error: " + (err?.message || "unknown"),
//     }));
//   }
// };