// flightapi/controllers/AirTicketing.js

const AirTicketingService = require("../services/AirTicketing");
const webEnquiry = require("../services/webEnquiryService");
const appEnquiry = require("../../BilldeskPG/services/retrieveTransaction.js");
const dbConnect = require("../configs/dbConnection");
require("dotenv").config();

const handleAirTicketing = async (req, res) => {
  try {
    const { orderid, channel, traceId } = req.body;

    /* =====================================================
       1. BASIC VALIDATION
       ===================================================== */
    if (!orderid || !channel || !traceId) {
      return res.status(400).json({
        success: false,
        message: "Missing required fields: orderid, channel, traceId",
      });
    }

    if (!["web", "app"].includes(channel)) {
      return res.status(400).json({
        success: false,
        message: "Invalid channel. Must be 'web' or 'app'",
      });
    }

    /* =====================================================
       2. FETCH TRANSACTION DETAILS FROM onlinepay
          WHERE ipgid = orderid
       ===================================================== */
    const [rows] = await dbConnect.query(
      `SELECT utranid, serviceref_id, tranamount, status, servicetype
         FROM onlinepay
        WHERE ipgid = ?
        LIMIT 1`,
      [orderid]
    );

    if (!rows || rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Transaction not found for the given orderid",
      });
    }

    const transaction = rows[0];
    console.log(`[${traceId}] Transaction fetched from onlinepay:`, transaction);

    /* =====================================================
       3. DUPLICATE CHECK
          If already success → block ticketing
       ===================================================== */
    if (transaction.status === "success") {
      return res.status(409).json({
        success: false,
        message: "Ticket already issued for this transaction. Duplicate request blocked.",
      });
    }

    /* =====================================================
       4. PAYMENT ENQUIRY — WEB or APP
       ===================================================== */
    let enquiryResult;

    if (channel === "web") {
      console.log(`[${traceId}] Calling Web BillDesk Enquiry...`);
      enquiryResult = await webEnquiry.processEnquirePayment(
        process.env.BD_MERCHANT_ID,
        orderid
      );
    } else {
      console.log(`[${traceId}] Calling App BillDesk Enquiry...`);
      enquiryResult = await appEnquiry.retrieveTransaction({ orderid });
    }

    console.log(`[${traceId}] Enquiry Result:`, enquiryResult);

    /* =====================================================
       5. VALIDATE PAYMENT STATUS
          Check auth_status — success code is "0300"
       ===================================================== */
    const authStatus =
      enquiryResult?.data?.auth_status ||
      enquiryResult?.data?.transaction_status ||
      null;

    if (authStatus !== "0300") {
      console.error(`[${traceId}] Payment not successful. auth_status: ${authStatus}`);
      return res.status(402).json({
        success: false,
        message: "Payment verification failed. Ticketing aborted.",
        auth_status: authStatus,
      });
    }

    console.log(`[${traceId}] Payment verified successfully.`);

    /* =====================================================
       6. UPDATE onlinepay STATUS TO 'success'
       ===================================================== */
    await dbConnect.query(
      `UPDATE onlinepay SET status = 'success' WHERE ipgid = ?`,
      [orderid]
    );
    console.log(`[${traceId}] onlinepay status updated to 'success'`);

    /* =====================================================
       7. FETCH PNR FROM Reservations TABLE
          WHERE traceId = traceId
       ===================================================== */
    const [reservationRows] = await dbConnect.query(
      `SELECT Airlocatorcode
         FROM Reservations
        WHERE traceId = ?
        LIMIT 1`,
      [traceId]
    );

    if (!reservationRows || reservationRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Reservation not found for the given traceId",
      });
    }

    const pnr = reservationRows[0].Airlocatorcode;
    console.log(`[${traceId}] PNR fetched from Reservations:`, pnr);

    /* =====================================================
       8. FETCH PRICING KEY FROM Farebreakdown TABLE
          WHERE traceId = traceId
       ===================================================== */
    const [fareRows] = await dbConnect.query(
      `SELECT pricingKey
         FROM Farebreakdown
        WHERE traceId = ?
        LIMIT 1`,
      [traceId]
    );

    if (!fareRows || fareRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Fare breakdown not found for the given traceId",
      });
    }

    const pricingKey = fareRows[0].pricingKey;
    console.log(`[${traceId}] PricingKey fetched from Farebreakdown:`, pricingKey);

    /* =====================================================
       9. HARDCODED FOP
       ===================================================== */
    const fop = { type: "Cash" };

    /* =====================================================
       10. CALL AIR TICKETING SERVICE
       ===================================================== */
    console.log(`[${traceId}] Proceeding to Air Ticketing...`);
    const result = await AirTicketingService.issueTicket(pnr, pricingKey, {
      fop,
      traceId,
    });

    /* =====================================================
       11. RETURN RESPONSE
       ===================================================== */
    return res.status(200).json({
      success: true,
      traceId: result.traceId,
      data: result.data,
    });

  } catch (error) {
    console.error(
      `[CONTROLLER-ERROR] TraceId: ${req.body?.traceId} - ${error.message}`
    );
    return res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

module.exports = { handleAirTicketing };