const User = require("../models/userModel");
const Appointment = require("../models/appointmentModel");
const Patient = require("../models/patientModel");
const Leave = require("../models/leaveModel");



// const getDoctorStats = async (req, res) => {
//     try {
//         const now = new Date();

//         const startOfDay = new Date(now.setHours(0, 0, 0, 0));
//         const endOfDay = new Date(now.setHours(23, 59, 59, 999));

//         //  Total Doctors
//         const totalDoctorsPromise = User.countDocuments({
//             role: "doctor",
//             status: "Approved",
//             isDeleted: false,
//         });

//         //  Doctors with any appointment today
//         const doctorsWithAppointmentsTodayPromise = Appointment.distinct(
//             "doctorId",
//             {
//                 date: { $gte: startOfDay, $lte: endOfDay },
//                 status: { $in: ["Booked", "Waiting"] },
//                 isDeleted: false,
//             }
//         );

//         //  Doctors busy RIGHT NOW (appointment happening now)
//         const busyDoctorsPromise = Appointment.distinct("doctorId", {
//             date: {
//                 $gte: new Date(now.getTime() - 30 * 60000), // 30 mins back
//                 $lte: new Date(now.getTime() + 30 * 60000), // 30 mins ahead
//             },
//             status: "Waiting",
//             isDeleted: false,
//         });

//         const [
//             totalDoctors,
//             doctorsWithAppointmentsToday,
//             busyDoctors,
//         ] = await Promise.all([
//             totalDoctorsPromise,
//             doctorsWithAppointmentsTodayPromise,
//             busyDoctorsPromise,
//         ]);

//         const availableToday = doctorsWithAppointmentsToday.length;
//         const busy = busyDoctors.length;
//         const free = totalDoctors - busy;

//         return res.json({
//             success: true,
//             data: {
//                 total: totalDoctors,
//                 availableToday,
//                 busy,
//                 free,
//             },
//         });
//     } catch (err) {
//         console.error("Doctor Stats Error:", err);
//         res.status(500).json({
//             success: false,
//             message: "Failed to fetch doctor stats",
//         });
//     }
// };
// const getDoctorStats = async (req, res) => {
//     try {
//         const today = new Date().toISOString().split("T")[0]; // "YYYY-MM-DD"
//         const todayStart = new Date();
//         todayStart.setHours(0, 0, 0, 0);

//         const todayEnd = new Date();
//         todayEnd.setHours(23, 59, 59, 999);
//         const now = new Date();
//         const currentMinutes =
//             now.getHours() * 60 + now.getMinutes(); // convert to minutes

//         // Total doctors
//         const totalDoctorsPromise = User.countDocuments({
//             role: "doctor",
//             status: "Approved",
//             isDeleted: false,
//         });

//         const doctorsOnLeaveToday = await Leave.distinct("employee", {
//             status: "Approved",
//             isDeleted: false,
//             startDate: { $lte: todayEnd },
//             endDate: { $gte: todayStart },
//         });

//         // Doctors having appointments today (Booked or Waiting)
//         // const doctorsWithAppointmentsTodayPromise = Appointment.distinct(
//         //     "doctor",
//         //     {
//         //         date: today,
//         //         status: { $in: ["Booked", "Waiting"] },
//         //         isDeleted: false,
//         //     }
//         // );
        
//         const availableDoctors = await User.find({
//             role: "doctor",
//             isDeleted: false,
//             _id: { $nin: doctorsOnLeaveToday },
//         });


//         // Busy doctors RIGHT NOW
//         const todayAppointments = await Appointment.find({
//             date: today,
//             status: "Waiting",
//             isDeleted: false,
//         }).select("doctor startTime endTime");

//         const busyDoctorSet = new Set();

//         todayAppointments.forEach((appt) => {
//             const [sh, sm] = appt.startTime.split(":").map(Number);
//             const [eh, em] = appt.endTime.split(":").map(Number);

//             const start = sh * 60 + sm;
//             const end = eh * 60 + em;

//             if (currentMinutes >= start && currentMinutes <= end) {
//                 busyDoctorSet.add(appt.doctor.toString());
//             }
//         });

//         const [totalDoctors, doctorsWithAppointmentsToday] = await Promise.all([
//             totalDoctorsPromise,
//             doctorsWithAppointmentsTodayPromise,
//         ]);

//         const availableToday = doctorsWithAppointmentsToday.length;
//         const busy = busyDoctorSet.size;
//         const free = totalDoctors - busy;

//         return res.json({
//             success: true,
//             data: {
//                 total: totalDoctors,
//                 availableToday,
//                 busy,
//                 free,
//             },
//         });
//     } catch (err) {
//         console.error("Doctor Stats Error:", err);
//         res.status(500).json({
//             success: false,
//             message: "Failed to fetch doctor stats",
//         });
//     }
// };
const getDoctorStats = async (req, res) => {
  try {
    const today = new Date().toISOString().split("T")[0];

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

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

    const now = new Date();
    const currentMinutes = now.getHours() * 60 + now.getMinutes();

    // 1️⃣ Total doctors
    const totalDoctorsPromise = User.countDocuments({
      role: "doctor",
      status: "Approved",
      isDeleted: false,
    });

    // 2️⃣ Doctors on leave today
    const doctorsOnLeaveTodayPromise = Leave.distinct("employee", {
      status: "Approved",
      isDeleted: false,
      startDate: { $lte: todayEnd },
      endDate: { $gte: todayStart },
    });

    // 3️⃣ Appointments today (for busy check)
    const todayAppointmentsPromise = Appointment.find({
      date: today,
      status: "Waiting",
      isDeleted: false,
    }).select("doctor startTime endTime");

    const [
      totalDoctors,
      doctorsOnLeaveToday,
      todayAppointments,
    ] = await Promise.all([
      totalDoctorsPromise,
      doctorsOnLeaveTodayPromise,
      todayAppointmentsPromise,
    ]);

    // Convert leave list to Set
    const leaveSet = new Set(doctorsOnLeaveToday.map(id => id.toString()));

    // 4️⃣ Find busy doctors RIGHT NOW
    const busyDoctorSet = new Set();

    todayAppointments.forEach((appt) => {
      const [sh, sm] = appt.startTime.split(":").map(Number);
      const [eh, em] = appt.endTime.split(":").map(Number);

      const start = sh * 60 + sm;
      const end = eh * 60 + em;

      if (currentMinutes >= start && currentMinutes <= end) {
        busyDoctorSet.add(appt.doctor.toString());
      }
    });

    // 5️⃣ Calculate stats
    const availableToday = totalDoctors - leaveSet.size;
    const busy = busyDoctorSet.size;
    const free = availableToday - busy;

    return res.json({
      success: true,
      data: {
        total: totalDoctors,
        availableToday,
        busy,
        free,
      },
    });
  } catch (err) {
    console.error("Doctor Stats Error:", err);
    res.status(500).json({
      success: false,
      message: "Failed to fetch doctor stats",
    });
  }
};



const getTodayAppointmentStats = async (req, res) => {

    try {
        const today = new Date().toISOString().split("T")[0]

        const stats = await Appointment.aggregate([
            {
                $match: {
                    date: today,
                    isDeleted: false,
                },
            },
            {
                $group: {
                    _id: "$status",
                    count: { $sum: 1 },
                },
            },
        ]);

        // Convert to map
        const map = {};
        stats.forEach((s) => {
            map[s._id] = s.count;
        });

        const completed = map["Completed"] || 0;
        const cancelled = map["Cancelled"] || 0;
        const booked = map["Booked"] || 0;
        const waiting = map["Waiting"] || 0;
        const noShow = map["No-Show"] || 0;

        const todaysBookings = booked + waiting + completed + noShow;
        const pending = booked + waiting;

        return res.json({
            success: true,
            data: {
                todaysBookings,
                completed,
                cancelled,
                pending,
            },
        });
    } catch (err) {
        console.error("Appointment Stats Error:", err);
        res.status(500).json({
            success: false,
            message: "Failed to fetch appointment stats",
        });
    }
};


const getPatientStatsToday = async (req, res) => {
    try {
        const today = new Date().toISOString().split("T")[0]; // "YYYY-MM-DD"

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

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

        //  Total patients
        const totalPatientsPromise = Patient.countDocuments({
            isDeleted: false,
        });

        //  New patients today
        const newTodayPromise = Patient.countDocuments({
            createdAt: { $gte: startOfDay, $lte: endOfDay },
            isDeleted: false,
        });

        //  Active today (patients with appointment today)
        const activeTodayPatientsPromise = Appointment.distinct("patient", {
            date: today,
            isDeleted: false,
        });

        //  Follow-up patients (patients having more than 1 appointment)
        const followUpsPromise = Appointment.aggregate([
            {
                $group: {
                    _id: "$patient",
                    count: { $sum: 1 },
                },
            },
            {
                $match: {
                    count: { $gt: 1 },
                },
            },
        ]);

        const [
            totalPatients,
            newToday,
            activeTodayPatients,
            followUps,
        ] = await Promise.all([
            totalPatientsPromise,
            newTodayPromise,
            activeTodayPatientsPromise,
            followUpsPromise,
        ]);

        return res.json({
            success: true,
            data: {
                total: totalPatients,
                newToday,
                followUps: followUps.length,
                activeToday: activeTodayPatients.length,
            },
        });
    } catch (err) {
        console.error("Patient Stats Error:", err);
        res.status(500).json({
            success: false,
            message: "Failed to fetch patient stats",
        });
    }
};


module.exports = {
    getDoctorStats,
    getTodayAppointmentStats,
    getPatientStatsToday,
};