
const { pool } = require("../../config/db");
const { errorResponse } = require("../../utils/errorResponseHandler");

// 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 getSecurityDashboardStats = async (req, res) => {
  const client = await pool.connect();

  try {
    //  TODAY RANGE
    const startOfDay = new Date();
    startOfDay.setHours(0, 0, 0, 0);

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

    //  PARALLEL QUERIES

    const [
      visitorsInsideRes,
      totalVehiclesRes,
      vehiclesInsideRes,
      vehiclesExitedRes,
      pendingApprovalsRes,
      recentVisitorsRes,
      recentVehiclesRes,
      parkingOccupiedRes,
    ] = await Promise.all([
      //  VISITORS INSIDE
      client.query(
        `
        SELECT COUNT(*) 
        FROM visitors
        WHERE gate_status = 'Inside'
        AND is_deleted = false
        `,
      ),

      //  TOTAL VEHICLES TODAY
      client.query(
        `
        SELECT COUNT(*) 
        FROM commercial_vehicles
        WHERE is_deleted = false
        AND created_at BETWEEN $1 AND $2
        `,
        [startOfDay, endOfDay],
      ),

      //  VEHICLES INSIDE
      client.query(
        `
        SELECT COUNT(*) 
        FROM commercial_vehicles
        WHERE gate_status = 'Inside'
        AND is_deleted = false
        AND created_at BETWEEN $1 AND $2
        `,
        [startOfDay, endOfDay],
      ),

      //  VEHICLES EXITED
      client.query(
        `
        SELECT COUNT(*) 
        FROM commercial_vehicles
        WHERE gate_status = 'Exited'
        AND is_deleted = false
        AND created_at BETWEEN $1 AND $2
        `,
        [startOfDay, endOfDay],
      ),

      //  PENDING APPROVALS
      client.query(
        `
        SELECT COUNT(*) 
        FROM visitors
        WHERE host_approval = 'Pending'
        AND is_deleted = false
        `,
      ),

      //  RECENT VISITORS
      client.query(
        `
        SELECT 
          visitor_name,
          gate_status,
          created_at,
          host_approval
        FROM visitors
        WHERE is_deleted = false
        ORDER BY created_at DESC
        LIMIT 5
        `,
      ),

      //  RECENT VEHICLES
      client.query(
        `
        SELECT 
          vehicle_number,
          created_at
        FROM commercial_vehicles
        WHERE is_deleted = false
        ORDER BY created_at DESC
        LIMIT 5
        `,
      ),

      //  PARKING OCCUPIED
      // client.query(
      //   `
      //   SELECT COUNT(*)
      //   FROM parking_bays
      //   WHERE status = 'PARKED'
      //   `
      // ),
      client.query(
        `
  SELECT COUNT(*) 
  FROM commercial_vehicles
  WHERE parking_id IS NOT NULL
  AND gate_status = 'Inside'
  AND is_deleted = false
  `,
      ),
    ]);


    const visitorsInside = Number(visitorsInsideRes.rows[0].count);

    const totalVehicles = Number(totalVehiclesRes.rows[0].count);

    const vehiclesInside = Number(vehiclesInsideRes.rows[0].count);

    const vehiclesExited = Number(vehiclesExitedRes.rows[0].count);

    const pendingApprovals = Number(pendingApprovalsRes.rows[0].count);

    const parkingOccupied = Number(parkingOccupiedRes.rows[0].count);


    const recentVisitors = recentVisitorsRes.rows;

    const recentVehicles = recentVehiclesRes.rows;

    const activities = [
      ...recentVisitors.map((v) => ({
        time: v.created_at,
        type:
          v.host_approval === "Approved"
            ? "APPV"
            : v.gate_status === "Inside"
              ? "IN"
              : "OUT",

        message:
          v.host_approval === "Approved"
            ? `Host approved visitor ${v.visitor_name}`
            : `Visitor ${v.visitor_name} ${
                v.gate_status === "Inside" ? "arrived" : "exited"
              }`,
      })),

      ...recentVehicles.map((v) => ({
        time: v.created_at,
        type: "IN",
        message: `Vehicle ${v.vehicle_number} 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,
          vehiclesInside: 0,
          vehiclesExited: 0,
          pendingApprovals: 0,
          parkingOccupied: 0,
        },

        recentActivities: [],
      },
    });
  } finally {
    client.release();
  }
};

// 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");
//   }
// };

const getQcDashboardStats = async (req, res) => {
  const client = await pool.connect();

  try {

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

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

  
    const [qcDoneTodayRes, qcWaitingRes] = await Promise.all([
      //  QC COMPLETED TODAY
      client.query(
        `
        SELECT COUNT(*) 
        FROM quality_checks
        WHERE is_deleted = false
        AND is_active = true
        AND complete_status = 'Completed'
        AND updated_at BETWEEN $1 AND $2
        `,
        [start, end],
      ),

      //  WAITING FOR QC
      client.query(
        `
        SELECT COUNT(*) 
        FROM commercial_vehicles
        WHERE qc_id IS NULL
        AND gate_status = 'Inside'
        AND is_deleted = false
        `,
      ),
    ]);

    const qcDoneToday = Number(qcDoneTodayRes.rows[0].count);

    const qcWaiting = Number(qcWaitingRes.rows[0].count);
    return res.status(200).json({
      success: true,
      data: {
        stats: {
          qcDoneToday,
          qcWaiting,
        },
      },
    });
  } catch (error) {
    console.error("QC DASHBOARD ERROR:", error);

    return errorResponse(res, "Failed to fetch QC Dashboard Stats", 500, error);
  } finally {
    client.release();
  }
};

module.exports = {
  getSecurityDashboardStats,
  getQcDashboardStats,
};
