const Parking = require("../../models/securityops/parkingModel");

exports.getCommercialParkingAvailability = async () => {
  const bays = await Parking.find({
    // category: "COMMERCIAL",
    // isActive: true,
    isDeleted: false
  }).lean();

  const result = bays.map((bay) => {
    // const occupied = bay.vehicles.length;
    // const occupied = bay.vehicles.length;
    const occupied = bay.vehicles.filter(v => v.status === "PARKED").length;
    const available = bay.capacity - occupied;

    let status = "AVAILABLE";

    if (occupied === bay.capacity) status = "FULL";
    else if (occupied > 0) status = "PARTIAL";

    return {
      id: bay._id,
      code: bay.code,
      type : bay.type,
      category : bay.category,
      capacity: bay.capacity,
      occupied,
      available,
      status,
      vehicles: bay.vehicles.map((v) => ({
        slot : v.slot,
        vehicleNumber: v.vehicleNumber,
        driverName: v.driverName,
        status: v.status,
        checkInTime: v.checkInTime
      }))
    };
  });

  return result;
};









// exports.getCommercialParkingAvailability = async () => {
//   const bays = await Parking.find({
//     category: "COMMERCIAL",
//     isDeleted: false,
//   }).lean();

//   const result = bays.map((bay) => {
//     const parkedVehicles = bay.vehicles.filter(
//       (v) => v.status === "PARKED"
//     );

//     const occupied = parkedVehicles.length;
//     const available = bay.capacity - occupied;

//     let status = "AVAILABLE";
//     if (occupied === bay.capacity) status = "FULL";
//     else if (occupied > 0) status = "PARTIAL";

//     /* ⭐ SLOT GRID GENERATION */
//     const slots = [];

//     for (let i = 1; i <= bay.capacity; i++) {
//       const vehicle = parkedVehicles.find((v) => v.slot === i);

//       slots.push({
//         slot: i,
//         status: vehicle ? "OCCUPIED" : "AVAILABLE",
//         vehicleNumber: vehicle?.vehicleNumber || null,
//         driverName: vehicle?.driverName || null,
//         checkInTime: vehicle?.checkInTime || null,
//       });
//     }

//     return {
//       id: bay._id,
//       code: bay.code,
//       capacity: bay.capacity,
//       occupied,
//       available,
//       status,
//       slots,   // ⭐ NEW IMPORTANT FIELD
//     };
//   });

//   return result;
// };