const { createFlightOrder } = require('../models/flightOrderModel');
const crypto = require("crypto");
const { v4: uuidv4 } = require('uuid');
const dbConnect   = require('../../busapi/configs/dbConnection');


async function flightOrderHandler(req, res) {
  try {
    console.log("Received booking request:", JSON.stringify(req.body, null, 2));

    const { data } = req.body;
    const travelers = data.travelers;

    if (!data || !data.flightOffers || !data.travelers) {
      return res.status(400).json({ error: "Missing required fields: flightOffers or travelers" });
    }
    
     if (!Array.isArray(travelers) || travelers.length === 0) {
    throw new Error("No passengers found in request body");
    }

    const orderResponse = await createFlightOrder(data);
    
    const internalId = uuidv4();
   
    const bookingRef = orderResponse.associatedRecords[0].reference;
    
    const amount = data.flightOffers[0].price.total;
    const customer_id = travelers[0].contact?.phones?.[0]?.number;
    
    const insertQuery1 = `
    INSERT INTO Bookings (
        internal_id, booking_ref, amadeus_order_id, customer_id, status, created_at, total_amount
        )VALUES (?, ?, ?, ?, 'Pending', NOW(), ?)`;
    
    const insertValues1 = [internalId, bookingRef, orderResponse.id, customer_id, amount];
   
    const [result1] = await dbConnect.query(insertQuery1, insertValues1);
    
    const booking_id = result1.insertId; 
  
    const insertQuery2 = `
        INSERT INTO Passengers (
        booking_id, first_name, last_name, category, gender, email, mobile
        ) VALUES ?
    `;
    

    // Step 3: Build an array of value sets
    const insertValues2 = travelers.map(traveler => {
    const first_name = traveler.name.firstName;
    const last_name = traveler.name.lastName;
    const gender = traveler.gender;
    const email = traveler.contact?.emailAddress || null;
    const mobile = traveler.contact?.phones?.[0]?.number || null;
    const category = "Adult";

    return [booking_id, first_name, last_name, category, gender, email, mobile];
    });

    // Step 4: Execute bulk insert query
    const [result2] = await dbConnect.query(insertQuery2, [insertValues2]);

    // console.log("Inserted passengers:", result2.affectedRows);

    // Storing flight info and link them with booking id
    const flights = orderResponse.flightOffers[0].itineraries[0].segments;

    // Insert flights 
    for (let i = 0; i < flights.length; i++) {
      const f = flights[i];
      const [flightResult] = await dbConnect.query(
        `INSERT INTO flights (flight_number, origin, destination, departure_time, arrival_time)
         VALUES (?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`,
        [f.carrierCode + f.number, f.departure.iataCode, f.arrival.iataCode, f.departure.at, f.arrival.at]
      );
      const flightId = flightResult.insertId;
     
    // inking flights and bookings in booking_fligts table
      await dbConnect.query(
        `INSERT INTO booking_flights (booking_id, flight_id, segment_order)
         VALUES (?, ?, ?)`,
        [booking_id, flightId, i + 1]
      );
     
    }
    
    console.log("Flight order (PNR) created successfully.");
    return res.status(200).json(orderResponse);

  } catch (error) {
    //   await conn.rollback();
    console.error("Flight order booking error:", error.message);
    console.error("Error Response Data:", error.response?.data);

    return res.status(500).json({
      error: "Failed to create flight booking",
      details: error.response?.data || error.message || "Unknown error occurred"
    });
  }
}

module.exports = { flightOrderHandler };
