const BlacklistVehicle = require("../../models/securityops/blacklistVehicleModel");
const CommercialVehicle = require("../../models/securityops/vehicleModel");

// const createBlacklistVehicle = async (req, res) => {
//   try {
//     const { plateNumber, reason } = req.body;

//     if (!plateNumber || !reason) {
//       return res.status(400).json({
//         success: false,
//         message: "Plate number and reason are required",
//       });
//     }

//     const existing = await BlacklistVehicle.findOne({
//       plateNumber: plateNumber.toUpperCase(),
//       isDeleted: false,
//     });

//     if (existing) {
//       return res.status(400).json({
//         success: false,
//         message: "Vehicle already blacklisted",
//       });
//     }

//     const vehicle = new BlacklistVehicle({
//       plateNumber: plateNumber.toUpperCase(),
//       reason,
//       addedBy: req.user?._id,
//     });

//     await vehicle.save();

//     return res.status(201).json({
//       success: true,
//       message: "Vehicle added to blacklist",
//       data: vehicle,
//     });
//   } catch (error) {
//     console.error("Blacklist Create Error:", error);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to add vehicle to blacklist",
//     });
//   }
// };
const createBlacklistVehicle = async (req, res) => {
  try {
    let { plateNumber, reason } = req.body;

    if (!plateNumber || !reason) {
      return res.status(400).json({
        success: false,
        message: "Plate number and reason are required",
      });
    }

    /* ===== NORMALIZE ===== */
    const plate = plateNumber.replace(/\s+/g, "").toUpperCase();

    /* ===== CHECK EXISTING (ACTIVE OR SOFT DELETED) ===== */
    let blacklist = await BlacklistVehicle.findOne({
      plateNumber: plate,
    });

    /*  UPSERT LOGIC */
    if (blacklist) {
      blacklist.reason = reason;
      blacklist.isDeleted = false;
      blacklist.isActive = true;
      blacklist.updatedBy = req.user?._id;
      blacklist.updatedAt = new Date();

      await blacklist.save();

    } else {

      blacklist = await BlacklistVehicle.create({
        plateNumber: plate,
        reason,
        addedBy: req.user?._id,
      });
    }

    /* ===== SYNC COMMERCIAL VEHICLE ===== */
    await CommercialVehicle.updateMany(
      {
        vehicleNumber: plate,
        isDeleted: false,
      },
      {
        $set: {
          blacklistId: blacklist._id,
          isBlacklisted: true,
          blacklistReason: reason,
        },
      }
    );

    return res.status(200).json({
      success: true,
      message: "Vehicle blacklisted successfully",
      data: blacklist,
    });

  } catch (error) {
    console.error("Blacklist Create Error:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to add vehicle to blacklist",
    });
  }
};

const getBlacklistVehicles = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;

    const skip = (page - 1) * limit;

    const vehicles = await BlacklistVehicle.find({
      isDeleted: false,
      isActive: true,
    })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    const total = await BlacklistVehicle.countDocuments({
      isDeleted: false,
    });

    return res.status(200).json({
      success: true,
      data: vehicles,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Fetch Blacklist Error:", error);
    return res.status(500).json({
      success: false,
      message: "Failed to fetch blacklist vehicles",
    });
  }
};

// const blacklistVehicle = async (req, res) => {
//   try {
//     const { vehicleNumber, reason } = req.body;

//     if (!vehicleNumber || !reason) {
//       return res.status(400).json({
//         success: false,
//         message: "Vehicle number & reason required"
//       });
//     }

//     /* 1️ Create blacklist entry */
//     const blacklist = await BlacklistVehicle.create({
//       plateNumber: vehicleNumber.toUpperCase(),
//       reason,
//       addedBy: req.user?._id
//     });

//     /* 2️ Link commercial vehicle */
//     await CommercialVehicle.updateMany(
//       {
//         vehicleNumber: vehicleNumber.toUpperCase(),
//         isDeleted: false
//       },
//       {
//         $set: {
//           blacklistId: blacklist._id,
//           isBlacklisted: true,
//           // gateStatus: "Blacklisted"
//         }
//       }
//     );

//     return res.json({
//       success: true,
//       message: "Vehicle blacklisted"
//     });

//   } catch (err) {
//     console.log(err);
//     return res.status(500).json({
//       success: false,
//       message: "Blacklist failed"
//     });
//   }
// };
const blacklistVehicle = async (req, res) => {
  try {
    const { vehicleNumber, reason } = req.body;

    if (!vehicleNumber || !reason) {
      return res.status(400).json({
        success: false,
        message: "Vehicle number & reason required",
      });
    }

    const plate = vehicleNumber.toUpperCase();

    let blacklist = await BlacklistVehicle.findOne({
      plateNumber: plate,
      isDeleted: false,
    });

    /* ⭐ If already exists → reactivate */
    if (blacklist) {
      blacklist.reason = reason;
      blacklist.isActive = true;
      blacklist.updatedBy = req.user?._id;

      await blacklist.save();
    } else {
      /* ⭐ create new */
      blacklist = await BlacklistVehicle.create({
        plateNumber: plate,
        reason,
        addedBy: req.user?._id,
      });
    }

    /* Link commercial vehicles */
    await CommercialVehicle.updateMany(
      {
        vehicleNumber: plate,
        isDeleted: false,
      },
      {
        $set: {
          blacklistId: blacklist._id,
          isBlacklisted: true,
        },
      },
    );

    return res.json({
      success: true,
      message: "Vehicle blacklisted",
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: "Blacklist failed",
    });
  }
};
const checkVehicleBlacklist = async (req, res) => {
  try {
    let { plateNumber } = req.params;

    if (!plateNumber) {
      return res.status(400).json({
        success: false,
        message: "Plate number required",
      });
    }

    // plateNumber = plateNumber.trim().toUpperCase();
    plateNumber = plateNumber
      .replace(/\s+/g, "") // remove spaces
      .toUpperCase();

    const blacklist = await BlacklistVehicle.findOne({
      plateNumber,
      isActive: true,
      isDeleted: false,
    }).select("reason plateNumber");

    if (blacklist) {
      return res.status(200).json({
        success: true,
        blocked: true,
        message: `Vehicle ${blacklist.plateNumber} is blacklisted`,
        reason: blacklist.reason,
      });
    }

    return res.status(200).json({
      success: true,
      blocked: false,
    });
  } catch (error) {
    console.error("Blacklist Check Error:", error);
    return res.status(500).json({
      success: false,
      message: "Server error",
    });
  }
};

const unblockVehicle = async (req, res) => {
  try {
    const { id } = req.params;

    const blacklist = await BlacklistVehicle.findOne({
      _id: id,
      isActive: true,
    });

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

    /* 1 deactivate blacklist entry */
    blacklist.isActive = false;
    await blacklist.save();

    /* 2️ emove blacklist from vehicles */
    await CommercialVehicle.updateMany(
      {
        blacklistId: blacklist._id,
      },
      {
        $set: {
          isBlacklisted: false,
        },
        $unset: {
          blacklistId: "",
        },
      },
    );

    return res.json({
      success: true,
      message: "Vehicle un-blacklisted successfully",
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: "Unblock failed",
    });
  }
};

module.exports = {
  createBlacklistVehicle,
  unblockVehicle,
  getBlacklistVehicles,
  blacklistVehicle,
  checkVehicleBlacklist,
};
