const parkingService = require("../../services/securityops/parkingServices");
// const CommercialVehicle = require("../../models/securityops/vehicleModel");
const Parking = require("../../models/securityops/parkingModel");

const createBay = async (req, res) => {
  try {
    const { code, type, capacity } = req.body;

    if (!code || !capacity) {
      return res.status(400).json({
        success: false,
        message: "All fields required",
      });
    }

    // if (!req.body.category) {
    //   req.body.category = null;
    // }

    const exists = await Parking.findOne({
      code: code.toUpperCase(),
      isDeleted: false,
    });

    if (exists) {
      return res.status(400).json({
        success: false,
        message: "Bay already exists",
      });
    }

    const bay = await Parking.create({
      code: code.toUpperCase(),
      // category,
      type,
      capacity,
      createdBy: req.user?._id,
    });

    return res.json({
      success: true,
      message: "Bay created successfully",
      data: bay,
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: "Failed to create bay",
    });
  }
};

const getCommercialParkingAvailability = async (req, res) => {
  try {
    const data = await parkingService.getCommercialParkingAvailability();

    res.status(200).json({
      success: true,
      message: "Parking availability fetched successfully",
      data,
    });
  } catch (error) {
    console.error(error);

    res.status(500).json({
      success: false,
      message: "Failed to fetch parking availability",
    });
  }
};

const assignSlot = async (req, res) => {
  try {
    const { bayCode, slot, vehicleNumber, driverName, referenceNo } = req.body;

    const bay = await Parking.findOne({ code: bayCode });
    if (!bay) {
      return res.status(404).json({
        success: false,
        message: "Bay not found",
      });
    }

    // const slotExists = bay.vehicles.find((v) => v.slot === Number(slot));
    const slotExists = bay.vehicles.some(
      (v) => v.slot === Number(slot) && ["PARKED", "INSIDE"].includes(v.status),
    );

    if (slotExists) {
      return res.status(400).json({
        success: false,
        message: "Slot already occupied",
      });
    }

    bay.vehicles.push({
      slot,
      vehicleNumber,
      driverName,
      referenceNo,
      timeIn: new Date(),
    });

    await bay.save();

    res.json({
      success: true,
      message: "Slot assigned successfully",
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: "Server error",
    });
  }
};

const updateBay = async (req, res) => {
  try {
    const { id } = req.params;
    const { category, type, capacity, status } = req.body;

    const bay = await Parking.findOne({
      _id: id,
      isDeleted: false,
    });

    if (!bay) {
      return res.status(404).json({
        success: false,
        message: "Bay not found",
      });
    }

    /* OCCUPIED SLOT COUNT */
    const occupiedCount = bay.vehicles.filter(
      (v) => v.status === "PARKED",
    ).length;

    /*  CAPACITY VALIDATION */
    if (capacity && capacity < occupiedCount) {
      return res.status(400).json({
        success: false,
        message: `Cannot reduce capacity below occupied slots (${occupiedCount})`,
      });
    }

    /* UPDATE FIELDS SAFELY */
    if (category) bay.category = category;
    if (type) bay.type = type;
    if (capacity) bay.capacity = capacity;
    if (status) bay.status = status;

    bay.updatedBy = req.user?._id;

    await bay.save();

    return res.json({
      success: true,
      message: "Bay updated successfully",
      data: bay,
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: "Failed to update bay",
    });
  }
};

module.exports = {
  getCommercialParkingAvailability,
  assignSlot,
  createBay,
  updateBay,
};
