// // const express = require('express')
// const CommercialVehicle = require("../../models/securityops/vehicleModel")
// const Visitor = require("../../models/securityops/visitorModel")
// const Parking = require("../../models/securityops/parkingModel")
// const authenticate = require("../../middlewares/authenticate")
// const authorize = require("../../middlewares/authorize")

// const getSecurityDashboardStats = async (req, res) => {
//   try {

//     const [
//       visitorsInside,
//       totalVehicles,
//       pendingApprovals,
//       parkingOccupied
//     ] = await Promise.all([

//       Visitor.countDocuments({
//         gateStatus: "Inside",
//         isDeleted: false
//       }),

//       CommercialVehicle.countDocuments({
//         isDeleted: false
//       }),

//       Visitor.countDocuments({
//         hostApproval: "Pending",
//         isDeleted: false
//       }),

//       Parking.countDocuments({
//         status: "OCCUPIED"
//       })

//     ]);

//     return res.json({
//       success: true,
//       data: {
//         visitorsInside,
//         totalVehicles,
//         pendingApprovals,
//         parkingOccupied
//       }
//     });

//   } catch (error) {
//     console.error(error);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to load dashboard stats"
//     });
//   }
// };

// module.exports = {
//     getSecurityDashboardStats,
// }

const CommercialVehicle = require("../../models/securityops/vehicleModel");
const Visitor = require("../../models/securityops/visitorModel");
const Parking = require("../../models/securityops/parkingModel");
const QualityCheck = require("../../models/securityops/qcModel");
const { errorResponse } = require("../../utils/errorResponseHandler");

// const getSecurityDashboardStats = async (req, res) => {
//   try {

//     const [
//       visitorsInside,
//       totalVehicles,
//       pendingApprovals,
//       parkingOccupied,
//       recentVisitors,
//       recentVehicles
//     ] = await Promise.all([

//       Visitor.countDocuments({
//         gateStatus: "Inside",
//         isDeleted: false
//       }),

//       CommercialVehicle.countDocuments({
//         isDeleted: false
//       }),

//       Visitor.countDocuments({
//         hostApproval: "Pending",
//         isDeleted: false
//       }),

//       Parking.countDocuments({
//         status: "OCCUPIED"
//       }),

//       //  Recent Visitor Activities
//       Visitor.find({ isDeleted: false })
//         .sort({ createdAt: -1 })
//         .limit(5)
//         .select("visitorName gateStatus createdAt hostApproval"),

//       //  Recent Vehicle Activities
//       CommercialVehicle.find({ isDeleted: false })
//         .sort({ createdAt: -1 })
//         .limit(5)
//         .select("vehicleNumber createdAt")
//     ]);

//     // Merge Activities
//     const activities = [

//       ...recentVisitors.map(v => ({
//         time: v.createdAt,
//         type:
//           v.hostApproval === "Approved"
//             ? "APPV"
//             : v.gateStatus === "Inside"
//             ? "IN"
//             : "OUT",
//         message:
//           v.hostApproval === "Approved"
//             ? `Host approved visitor ${v.visitorName}`
//             : `Visitor ${v.visitorName} ${v.gateStatus === "Inside" ? "arrived" : "exited"}`
//       })),

//       ...recentVehicles.map(v => ({
//         time: v.createdAt,
//         type: "IN",
//         message: `Vehicle ${v.vehicleNumber} entered`
//       }))

//     ]
//       .sort((a, b) => new Date(b.time) - new Date(a.time))
//       .slice(0, 5);

//     return res.status(200).json({
//       success: true,
//       message: "Security dashboard data fetched",
//       data: {
//         stats: {
//           visitorsInside,
//           totalVehicles,
//           pendingApprovals,
//           parkingOccupied
//         },
//         recentActivities: activities
//       }
//     });

//   } catch (error) {
//     console.error("SECURITY DASHBOARD ERROR:", error);

//     return res.status(200).json({
//       success: true,
//       message: "Dashboard loaded with fallback",
//       data: {
//         stats: {
//           visitorsInside: 0,
//           totalVehicles: 0,
//           pendingApprovals: 0,
//           parkingOccupied: 0
//         },
//         recentActivities: []
//       }
//     });
//   }
// };
const startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);

const endOfDay = new Date();
endOfDay.setHours(23, 59, 59, 999);

const getSecurityDashboardStats = async (req, res) => {
  try {
    const [
      visitorsInside,
      totalVehicles,
      vehiclesInside,
      vehiclesExited,
      pendingApprovals,
      recentVisitors,
      recentVehicles,
      parkingDocs,
    ] = await Promise.all([
      Visitor.countDocuments({
        gateStatus: "Inside",
        isDeleted: false,
      }),

      CommercialVehicle.countDocuments({
        isDeleted: false,
        createdAt: {
          $gte: startOfDay,
          $lte: endOfDay,
        },
      }),

      CommercialVehicle.countDocuments({
        gateStatus: "Inside",
        isDeleted: false,
        createdAt: {
          $gte: startOfDay,
          $lte: endOfDay,
        },
      }),

      CommercialVehicle.countDocuments({
        gateStatus: "Exited",
        isDeleted: false,
        createdAt: {
          $gte: startOfDay,
          $lte: endOfDay,
        },
      }),

      Visitor.countDocuments({
        hostApproval: "Pending",
        isDeleted: false,
      }),

      Visitor.find({ isDeleted: false })
        .sort({ createdAt: -1 })
        .limit(5)
        .select("visitorName gateStatus createdAt hostApproval"),

      CommercialVehicle.find({ isDeleted: false })
        .sort({ createdAt: -1 })
        .limit(5)
        .select("vehicleNumber createdAt"),

      Parking.find().select("capacity vehicles"),
    ]);

    // ⭐ Parking Occupied Calculation
    // let parkingOccupied = 0;

    // parkingDocs.forEach(p => {
    //   const parkedCount = p.vehicles.filter(
    //     v => v.status === "PARKED"
    //   ).length;

    //   if (parkedCount > 0) parkingOccupied++;
    // });

    let parkingOccupied = 0;
    parkingDocs.forEach((p) => {
      const parkedCount = p.vehicles.filter(
        (v) => v.status === "PARKED",
      ).length;

      parkingOccupied += parkedCount;
    });

    // ⭐ Merge Activities
    const activities = [
      ...recentVisitors.map((v) => ({
        time: v.createdAt,
        type:
          v.hostApproval === "Approved"
            ? "APPV"
            : v.gateStatus === "Inside"
              ? "IN"
              : "OUT",
        message:
          v.hostApproval === "Approved"
            ? `Host approved visitor ${v.visitorName}`
            : `Visitor ${v.visitorName} ${v.gateStatus === "Inside" ? "arrived" : "exited"}`,
      })),

      ...recentVehicles.map((v) => ({
        time: v.createdAt,
        type: "IN",
        message: `Vehicle ${v.vehicleNumber} entered`,
      })),
    ]
      .sort((a, b) => new Date(b.time) - new Date(a.time))
      .slice(0, 5);

    return res.status(200).json({
      success: true,
      message: "Security dashboard data fetched",
      data: {
        stats: {
          visitorsInside,
          totalVehicles,
          vehiclesInside,
          vehiclesExited,
          pendingApprovals,
          parkingOccupied,
        },
        recentActivities: activities,
      },
    });
  } catch (error) {
    console.error("SECURITY DASHBOARD ERROR:", error);

    return res.status(200).json({
      success: true,
      message: "Dashboard loaded with fallback",
      data: {
        stats: {
          visitorsInside: 0,
          totalVehicles: 0,
          pendingApprovals: 0,
          parkingOccupied: 0,
        },
        recentActivities: [],
      },
    });
  }
};

const getQcDashboardStats = async (req, res) => {
  try {
    /* ================= TODAY DATE RANGE ================= */

    const start = new Date();
    start.setHours(0, 0, 0, 0);

    const end = new Date();
    end.setHours(23, 59, 59, 999);

    /* ================= TODAY QC DONE ================= */

    const qcDoneTodayAgg = await QualityCheck.aggregate([
      {
        $match: {
          isDeleted: false,
          isActive: true,
          completeStatus: "Completed",
          updatedAt: { $gte: start, $lte: end },
        },
      },
      {
        $count: "total",
      },
    ]);

    const qcDoneToday = qcDoneTodayAgg.length > 0 ? qcDoneTodayAgg[0].total : 0;

    /* ================= WAITING FOR QC ================= */

    const waitingQcAgg = await CommercialVehicle.aggregate([
      {
        $match: {
          qcId: null,
          gateStatus: "Inside",
          isDeleted: false,
        },
      },
      {
        $count: "total",
      },
    ]);

    const qcWaiting = waitingQcAgg.length > 0 ? waitingQcAgg[0].total : 0;

    /* ================= RESPONSE ================= */

    return res.status(200).json({
      success: true,
      data: {
        stats: {
          qcDoneToday,
          qcWaiting,
        },
      },
    });
  } catch (error) {
    console.error("QC DASHBOARD ERROR:", error);
    return errorResponse(res, 500, "Failed to fetch QC Dashboard Stats");
  }
};

module.exports = {
  getSecurityDashboardStats,
  getQcDashboardStats,
};
