// flightbilldeskpg/services/billdeskService.js

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

async function createOrder(body) {
  console.log("Flight BillDesk createOrder request received");

  /* =====================================================
     1. BASIC VALIDATION
     ===================================================== */
  if (
    !body ||
    !body.amount ||
    !body.universal_locator_code ||
    !body.user_id ||
    !body.paymentfor ||
    !body.customer ||
    !body.customer.first_name ||
    !body.customer.last_name
  ) {
    const err = new Error(
      "Missing required fields: amount, universal_locator_code, user_id, paymentfor, customer(first_name, last_name)"
    );
    err.statusCode = 400;
    throw err;
  }

  const {
    amount,
    universal_locator_code,
    air_locator_code,
    provider_locator_code,
    user_id,
    paymentfor,
    customer,
  } = body;

  console.log("Flight BillDesk createOrder - validation passed");

  /* =====================================================
     2. GENERATE MERCHANT ORDER ID
     ===================================================== */
  const orderid = `BDPG${Date.now()}`;
  console.log("orderid: ", orderid);

  /* =====================================================
     3. ORDER DATE (YYYY-MM-DDThh:mm:ssTZD)
     ===================================================== */
  const now = new Date();
  const isoString = now.toISOString().split(".")[0];
  const offsetMinutes = now.getTimezoneOffset();
  const sign = offsetMinutes <= 0 ? "+" : "-";
  const hours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
  const minutes = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
  const orderDate = `${isoString}${sign}${hours}:${minutes}`;

  /* =====================================================
     4. DB INSERT INTO onlinepay (status = 'initiated')
        Mapping:
          tranamount   <- amount
          payeename    <- customer.first_name + customer.last_name
          serviceref_id <- universal_locator_code  (UR locator, primary reference)
          ipgid        <- 0 (placeholder, updated after BillDesk call)
          payeeid      <- user_id
          servicetype  <- paymentfor ("flight")
          status       <- 'initiated'
     ===================================================== */
  const insertQuery = `
    INSERT INTO onlinepay
      (tranamount, payeename, serviceref_id, ipgid, payeeid, servicetype, status)
    VALUES (?, ?, ?, 0, ?, ?, 'initiated')
  `;

  const [insertResult] = await dbConnect.query(insertQuery, [
    Number(amount).toFixed(2),
    `${customer.first_name} ${customer.last_name}`,
    universal_locator_code,
    user_id,
    paymentfor,
  ]);

  const utranid = insertResult.insertId;
  console.log("Flight DB insert done, utranid:", utranid);

  /* =====================================================
     5. BUILD BILLDESK PAYLOAD
        additional_info mapping:
          additional_info1 <- paymentfor            ("flight")
          additional_info2 <- universal_locator_code (primary UR reference)
          additional_info3 <- amount
          additional_info4 <- air_locator_code      (Air reservation locator)
          additional_info5 <- provider_locator_code (GDS/Provider PNR)
          additional_info6 <- "NA"
          additional_info7 <- "NA"
     ===================================================== */
  const payload = {
    orderid,
    mercid: process.env.BD_MERCHANT_ID,
    order_date: orderDate,
    amount: Number(amount).toFixed(2),
    currency: "356",
    ru: process.env.BD_RETURN_URL,
    itemcode: "DIRECT",
    mandate_required: "N",
    device: {
      init_channel: body.init_channel || "internet",
      ip: body.ip || "192.168.0.1",
      user_agent:
        body.user_agent ||
        "Mozilla/5.0(WindowsNT10.0;WOW64;rv:51.0)Gecko/20100101Firefox/51.0",
      accept_header:
        body.accept_header ||
        "application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    },
    additional_info: {
      additional_info1: paymentfor,
      additional_info2: universal_locator_code,
      additional_info3: String(amount),
      additional_info4: air_locator_code || "NA",
      additional_info5: provider_locator_code || "NA",
      additional_info6: "NA",
      additional_info7: "NA",
    },
  };

  /* =====================================================
     6. CALL BILLDESK CREATE ORDER API
     ===================================================== */
  const clientId = process.env.BD_CLIENT_ID || process.env.BD_MERCHANT_ID_UAT;
  console.log("Flight Create Order Request Payload:", payload);

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

  /* =====================================================
     7. DB UPDATE — STORE BILLDESK ORDER ID
     ===================================================== */
  const updateQuery = `
    UPDATE onlinepay
       SET ipgid = ?
     WHERE utranid = ?
  `;

  await dbConnect.query(updateQuery, [
    billdeskResponse.orderid || null,
    utranid,
  ]);

  console.log("Flight DB update done — ipgid stored for utranid:", utranid);

  /* =====================================================
     8. RETURN RESPONSE TO CONTROLLER
     ===================================================== */
  return {
    utranid,
    orderid,
    bdorderid: billdeskResponse.bdorderid || null,
    next_step: billdeskResponse.next_step || null,
    links: billdeskResponse.links || [],
    raw: billdeskResponse,
  };
}

module.exports = { createOrder };

