const User = require("../../models/userModel");
const Appointment = require("../../models/Appointment");
const sendMessage = require("../../utils/sendMessage");
const moment = require("moment");
const cron = require("node-cron");
const DoctorTimeSlot = require("../../models/TimeSlot");
const mongoose = require("mongoose");
const Therapy = require("../../models/Therapy");
const Plans = require("../../models/Plan");

// exports.getAllDoctorAppointments = async (req, res) => {
//   const doctorId = req.user?.id;

//   try {
//     const appointments = await Appointment.find({
//       doctor: doctorId,
//       status: { $nin: ["pending", "cancelled"] },
//     })
//       .populate("patient", "fullname email mobile")
//       .sort({ createdAt: -1 });

//     return res.status(200).json({
//       success: true,
//       message: "All appointments for doctor fetched successfully",
//       data: appointments,
//     });
//   } catch (error) {
//     console.error("Fetch Doctor Appointments Error:", error);
//     return res.status(500).json({
//       success: false,
//       message: "Server Error",
//     });
//   }
// };
exports.getAllDoctorAppointments = async (req, res) => {
  const doctorId = req.user?.id;

  // Pagination
  let {
    page = 1,
    limit = 10,
    status,
    fromDate,
    toDate,
    patientName,
  } = req.query;
  page = parseInt(page);
  limit = parseInt(limit);

  // Build filters
  let filters = {
    doctor: doctorId,
    status: { $nin: ["pending", "cancelled"] },
  };

  if (status) {
    filters.status = status;
  }
  if (fromDate || toDate) {
    filters.createdAt = {};
    if (fromDate) filters.createdAt.$gte = new Date(fromDate);
    if (toDate) filters.createdAt.$lte = new Date(toDate);
  }

  try {
    // Find patients if patientName filter is provided
    let patientIds = null;
    if (patientName) {
      const patients = await User.find({
        fullname: { $regex: patientName, $options: "i" },
        role: "patient",
      }).select("_id");
      patientIds = patients.map((p) => p._id);
      filters.patient = { $in: patientIds };
    }

    // Count total docs for pagination info
    const total = await Appointment.countDocuments(filters);

    // Find appointments
    const appointments = await Appointment.find(filters)
      .populate("patient", "fullname email mobile")
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(limit);

    return res.status(200).json({
      success: true,
      message: "All appointments for doctor fetched successfully",
      data: appointments,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Fetch Doctor Appointments Error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

exports.getDoctorSessionRequests = async (req, res) => {
  const doctorId = req.user?.id;

  try {
    const sessions = await Appointment.find({
      doctor: doctorId,
      status: { $ni: "pending" },
    })
      .populate("patient", "fullname email mobile")
      .sort({ createdAt: -1 });

    res.status(200).json({
      success: true,
      message: "Doctor's session requests fetched",
      data: sessions,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ success: false, message: "Server Error" });
  }
};

exports.acceptSessionRequest = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId, meetingLink } = req.body;

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

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
      status: { $ne: "pending" },
    });
    if (!session) {
      return res
        .status(404)
        .json({ success: false, message: "Session not found" });
    }
    console.log("reeached", session.doctor);
    if (session.doctor.toString() !== doctorId) {
      return res
        .status(403)
        .json({ success: false, message: "Unauthorized access" });
    }

    // Update session
    session.meetLink = meetingLink;
    session.status = "scheduled";
    await session.save();

    // Get user details for notification
    const user = await User.findById(session.patient);
    if (!user) {
      return res
        .status(404)
        .json({ success: false, message: "User not found" });
    }

    const fullPhone = `${user.countryCode}${user.mobile}`;
    const message = `Hi ${
      user.fullname
    }, your session has been accepted.\nMeeting Link: ${meetingLink}\nTime: ${new Date(
      session.startTime
    ).toLocaleString()} - ${new Date(session.endTime).toLocaleString()}`;

    // Send message (WhatsApp/SMS + Email)
    // await sendMessage(fullPhone, message, user.email, user._id);

    res.status(200).json({
      success: true,
      message: "Session request accepted and user notified",
      data: session,
    });
  } catch (err) {
    console.error("Accept Session Error:", err);
    res.status(500).json({ success: false, message: "Server Error" });
  }
};

exports.cancelAppointment = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId } = req.body;

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

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
      status: { $ne: "pending" },
    });
    if (!session) {
      return res
        .status(404)
        .json({ success: false, message: "Appointment not found" });
    }

    // Ensure only the assigned doctor can cancel
    if (session.doctor.toString() !== doctorId) {
      return res.status(403).json({
        success: false,
        message: "Only the assigned doctor can cancel this appointment",
      });
    }

    // Prevent cancelling completed sessions
    if (session.status === "completed") {
      return res
        .status(400)
        .json({ success: false, message: "Cannot cancel a completed session" });
    }

    // Mark appointment as cancelled
    session.status = "cancelled";
    await session.save();

    // Notify patient (optional)
    const patient = await User.findById(session.patient);
    if (patient) {
      const fullPhone = `${patient.countryCode}${patient.mobile}`;
      const message = `Hi ${
        patient.fullname
      }, your session scheduled on ${new Date(
        session.date
      ).toLocaleDateString()} at ${
        session.timeSlot.startTime
      } has been cancelled by the doctor.`;
      // await sendMessage(fullPhone, message, patient.email, patient._id);
    }

    return res.status(200).json({
      success: true,
      message: "Appointment cancelled successfully by doctor",
      data: session,
    });
  } catch (error) {
    console.error("Doctor cancel appointment error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

exports.completeAppointment = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId } = req.body;

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

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
      status: { $ne: "pending" },
    });
    if (!session) {
      return res
        .status(404)
        .json({ success: false, message: "Appointment not found" });
    }

    // Ensure only the assigned doctor can complete
    if (session.doctor.toString() !== doctorId) {
      return res.status(403).json({
        success: false,
        message: "Only the assigned doctor can complete this appointment",
      });
    }

    // --- PLAN LOGIC STARTS HERE ---
    const plan = await Plans.findOne({
      userId: session.patient,
      doctorId: session.doctor,
      // optionally, you might want: status: {$in: ['active','pending']}
    });

    if (plan) {
      if (plan.status === "active") {
        if (plan.unlockedSessions > 0) {
          plan.unlockedSessions -= 1;
          plan.completedSessions += 1;
        } else {
          return res.status(400).json({
            success: false,
            message: "No unlocked sessions remaining in the plan",
          });
        }
        await plan.save();
      } else if (plan.status === "pending") {
        plan.completedSessionsIndividual += 1;
        await plan.save();
      }
      // if plan is completed/cancelled, do nothing extra
    }
    // --- PLAN LOGIC ENDS HERE ---

    session.status = "completed";
    await session.save();

    const patient = await User.findById(session.patient);
    if (patient) {
      const fullPhone = `${patient.countryCode}${patient.mobile}`;
      const FEEDBACK_LINK = `https://your-frontend-domain.com/feedback/${session._id}`;
      const message = `Hi ${patient.fullname}, your session on ${new Date(
        session.date
      ).toLocaleDateString()} at ${
        session.timeSlot.startTime
      } has been successfully completed. We’d love to hear your feedback: ${FEEDBACK_LINK}`;
      // await sendMessage(fullPhone, message, patient.email, patient._id);
    }

    return res.status(200).json({
      success: true,
      message: "Appointment completed successfully by doctor",
      data: session,
    });
  } catch (error) {
    console.error("Doctor complete appointment error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

exports.addNotesToAppointment = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId, notes } = req.body;

  if (!sessionId || !notes?.trim()) {
    return res.status(400).json({
      success: false,
      message: "Both sessionId and notes are required",
    });
  }

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
      status: { $ne: "pending" },
    }).populate("patient", "fullname email mobile countryCode");

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

    // Ensure only assigned doctor can add notes
    if (session.doctor.toString() !== doctorId) {
      return res.status(403).json({
        success: false,
        message: "Only the assigned doctor can add notes",
      });
    }

    // Check if session start time has passed (allow notes after session start time)
    const now = new Date();
    const sessionDate = new Date(session.date);
    const [hours, minutes] = session.timeSlot.startTime.split(":");
    sessionDate.setHours(parseInt(hours), parseInt(minutes), 0, 0);

    if (now < sessionDate) {
      return res.status(400).json({
        success: false,
        message: "Notes can only be added after session start time",
      });
    }

    session.notes = notes.trim();
    await session.save();

    return res.status(200).json({
      success: true,
      message: "Notes added successfully",
      data: session,
    });
  } catch (error) {
    console.error("Add notes error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

exports.attachPdfToAppointment = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId } = req.body;

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

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
      status: { $ne: "pending" },
    });
    if (!session) {
      return res
        .status(404)
        .json({ success: false, message: "Appointment not found" });
    }

    // Ensure only assigned doctor can add notes
    if (session.doctor.toString() !== doctorId) {
      return res.status(403).json({
        success: false,
        message: "Only the assigned doctor can add Pdf",
      });
    }

    if (session.status !== "completed") {
      return res.status(400).json({
        success: false,
        message: "Pdf can only be added to completed sessions",
      });
    }

    session.pdf = req.file.path;
    await session.save();

    return res.status(200).json({
      success: true,
      message: "Pdf added successfully",
      data: session,
    });
  } catch (error) {
    console.error("Add Pdf error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

exports.getTodayAppointments = async (req, res) => {
  try {
    const doctorId = req.user.id;
    const todayStart = moment().startOf("day").toDate();
    const todayEnd = moment().endOf("day").toDate();

    const appointments = await Appointment.find({
      doctor: doctorId,
      date: { $gte: todayStart, $lte: todayEnd },
      status: { $in: ["scheduled", "completed", "cancelled"] },
    })
      .populate("patient", "fullname email mobile countryCode")
      .sort({ date: 1 });

    res.status(200).json({
      success: true,
      appointments,
    });
  } catch (error) {
    console.error("Error fetching today's appointments:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
};

exports.userTherapyDetails = async (req, res) => {
  const userId = req.query.id;

  if (!userId) {
    return res
      .status(400)
      .json({ success: false, message: "User ID is required" });
  }

  try {
    const user = await User.findById(userId).populate("therapy");

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

    if (!user.therapy) {
      return res
        .status(404)
        .json({ success: false, message: "Therapy not found for user" });
    }

    return res.status(200).json({
      success: true,
      message: "Therapy data fetched successfully",
      data: user.therapy,
    });
  } catch (error) {
    console.error("Error in fetching therapy details:", error);
    return res.status(500).json({ success: false, message: "Server error" });
  }
};

exports.getUpcomingAppointments = async (req, res) => {
  try {
    const doctorId = req.user.id;
    const now = new Date();

    const appointments = await Appointment.find({
      doctor: doctorId,
      date: { $gt: now },
      status: "scheduled",
    })
      .populate("patient", "fullname email")
      .sort({ date: 1 });

    res.status(200).json({
      success: true,
      appointments,
    });
  } catch (error) {
    console.error("Error fetching upcoming appointments:", error);
    res.status(500).json({ success: false, message: "Server error" });
  }
};

exports.getDoctorSessionStats = async (req, res) => {
  const doctorId = req.user?.id;

  try {
    const todayStart = moment().startOf("day").toDate();
    const todayEnd = moment().endOf("day").toDate();

    const totalSessions = await Appointment.countDocuments({
      doctor: doctorId,
      status: { $ne: "pending" },
    });
    const completedSessions = await Appointment.countDocuments({
      doctor: doctorId,
      status: "completed",
    });
    const cancelledSessions = await Appointment.countDocuments({
      doctor: doctorId,
      status: "cancelled",
    });
    const scheduledSessions = await Appointment.countDocuments({
      doctor: doctorId,
      status: "scheduled",
    });

    const todaySessions = await Appointment.countDocuments({
      doctor: doctorId,
      date: { $gte: todayStart, $lte: todayEnd },
      status: { $nin: ["cancelled", "pending"] },
    });

    res.status(200).json({
      success: true,
      message: "Doctor session statistics fetched successfully",
      data: {
        totalSessions,
        completedSessions,
        cancelledSessions,
        scheduledSessions,
        todaySessions,
      },
    });
  } catch (error) {
    console.error("Error fetching doctor session stats:", error);
    res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

cron.schedule("*/5 * * * *", async () => {
  console.log("Running session reminder check...");

  const now = new Date();
  const thirtyMinutesLater = moment(now).add(30, "minutes").toDate();

  try {
    const upcomingSessions = await Appointment.find({
      status: "scheduled",
      reminderSent: false,
      date: {
        $lte: thirtyMinutesLater,
        $gte: moment(now).add(25, "minutes").toDate(),
      },
    }).populate("patient", "fullname email mobile countryCode");

    for (const session of upcomingSessions) {
      const patient = session.patient;
      if (!patient) continue;

      const fullPhone = `${patient.countryCode}${patient.mobile}`;
      const message = `Hi ${patient.fullname}, this is a reminder that your session is scheduled in 30 minutes.\nMeeting Link: ${session.meetLink}`;

      // await sendMessage(fullPhone, message, patient.email, patient._id);

      session.reminderSent = true;
      await session.save();

      console.log(`Reminder sent to ${patient.fullname}`);
    }
  } catch (error) {
    console.error("Reminder job error:", error);
  }
});

exports.getDoctorsSelectedSlots = async (req, res) => {
  console.log("Fetching doctor's selected slots...");
  try {
    const doctorId = req.user.id;
    // Optional: Validate doctorId is a valid MongoDB ObjectId
    if (!doctorId || !mongoose.Types.ObjectId.isValid(doctorId)) {
      return res.status(400).json({ message: "Invalid or missing doctor ID." });
    }

    console.log(`Fetching selected slots for doctor: ${doctorId}`);

    // Query the database for the doctor's slots
    const timeSlots = await DoctorTimeSlot.findOne({ doctor: doctorId })
      .populate("doctor", "name email") // Optional: populate doctor details
      .lean();

    if (!timeSlots) {
      return res
        .status(404)
        .json({ message: "No slots found for this doctor." });
    }

    // Respond with the doctor's selected slots
    return res.status(200).json({
      doctor: timeSlots.doctor,
      slots: timeSlots.slots,
    });
  } catch (error) {
    console.error("Error fetching doctor's slots:", error);
    return res.status(500).json({ message: "Internal server error." });
  }
};

exports.planDetails = async (req, res) => {
  try {
    const therapyPlans = [
      "Art-based Therapy",
      "Acceptance and commitment therapy",
      "Behavioral Therapy",
      "Body Mind Psychotherapy",
      "Cognitive Hypnotic Coaching",
      "Cognitive behavioral therapy",
      "Dance or Movement Therapy",
      "Dialectical Behavioral Therapy",
      "Emotion-focused therapy",
      "Emotionally Focused Couples Therapy",
      "Existential Psychotherapy",
      "Family Systems Therapy",
      "Holistic Psychotherapy",
      "Integral Somatic Psychotherapy",
      "Interpersonal Therapy",
      "Internal Family Systems",
      "Mindfulness-Based Approaches",
      "Parent-Child Interaction Therapy",
      "Parent Work",
      "Positive Psychotherapy",
      "Psychoanalytic Psychotherapist",
      "Reality Therapy",
      "Self Psychology",
      "Sex therapy",
      "Somatic Psychotherapy",
      "Transactional Analysis",
      "Trauma-Focused Cognitive Behavioral Therapy",
    ];

    const goalPlans = [
      "Facilitating Behaviour change",
      "Improving relationships",
      "Facilitate client potentials",
      "Promote decision making",
      "Enhance your potential and enrich your self-development",
      "Developmental goals",
      "Emotional development",
      "Emotional exploration",
      "Making positive and healthy changes in life",
      "Improve communication of feelings, wants, and needs",
      "Exploring stress",
      "Improving self-esteem",
      "Resolving unhealed wounds and trauma",
      "Improve the client’s ability to establish and maintain a relationship",
      "Enhancing the client’s effectiveness",
      "Enhancing the ability to cope",
      "Explore your needs and wants",
      "Find ways to manage stres",
      "Find ways to manage depression",
      "Find ways to manage anxiety",
      "Boundary setting",
      "Coping with negative feelings",
      "Engage in healthier habits",
      "Manage your overthinking",
      "Reducing negative self-talk",
      "Sharpening your boundary-setting skills",
      "Discover yourself",
      "Practicing self-compassion",
    ];

    res.json({ therapyPlans, goalPlans });
  } catch (err) {
    console.error("Error in /therapy-goals", err);
    res
      .status(500)
      .json({ message: "Failed to fetch plans", error: err.message });
  }
};

exports.addPlan = async (req, res) => {
  try {
    const { userId, therapyPlans, goalPlans, amount, sessionCount } = req.body;
    const doctorId = req.user?.id;
    // Validation
    if (!userId || !therapyPlans || !goalPlans || !amount || !sessionCount) {
      return res.status(400).json({ message: "All fields are required." });
    }

    const newPlan = new Plans({
      userId,
      doctorId,
      therapyPlans,
      goalPlans,
      amount,
      sessionCount,
      status: "pending",
    });

    await newPlan.save();

    return res.status(201).json({
      message: "Plan added successfully",
      data: newPlan,
    });
  } catch (error) {
    console.error("Add Plan Error:", error);
    return res.status(500).json({
      message: "Failed to add plan",
      error: error.message,
    });
  }
};

exports.editPlan = async (req, res) => {
  try {
    const { planId } = req.params;
    const doctorId = req.user?.id;

    // Check for planId
    if (!planId) {
      return res.status(400).json({ message: "Plan ID is required." });
    }

    // Retrieve the existing plan
    const existingPlan = await Plans.findById(planId);
    if (!existingPlan) {
      return res.status(404).json({ message: "Plan not found." });
    }

    // Ensure the doctor owns the plan
    if (existingPlan.doctorId.toString() !== doctorId) {
      return res
        .status(403)
        .json({ message: "Unauthorized to edit this plan." });
    }

    // Prepare an object to collect updates
    const updates = {};

    // Only validate and update fields if they are provided
    if (req.body.userId !== undefined) {
      if (!req.body.userId) {
        return res.status(400).json({ message: "userId cannot be empty." });
      }
      updates.userId = req.body.userId;
    }

    if (req.body.therapyPlans !== undefined) {
      if (
        !Array.isArray(req.body.therapyPlans) ||
        req.body.therapyPlans.length === 0
      ) {
        return res
          .status(400)
          .json({ message: "therapyPlans must be a non-empty array." });
      }
      updates.therapyPlans = req.body.therapyPlans;
    }

    if (req.body.goalPlans !== undefined) {
      if (
        !Array.isArray(req.body.goalPlans) ||
        req.body.goalPlans.length === 0
      ) {
        return res
          .status(400)
          .json({ message: "goalPlans must be a non-empty array." });
      }
      updates.goalPlans = req.body.goalPlans;
    }

    if (req.body.amount !== undefined) {
      if (isNaN(req.body.amount) || req.body.amount < 0) {
        return res
          .status(400)
          .json({ message: "amount must be a non-negative number." });
      }
      updates.amount = req.body.amount;
    }

    if (req.body.sessionCount !== undefined) {
      if (
        !Number.isInteger(req.body.sessionCount) ||
        req.body.sessionCount < 0
      ) {
        return res
          .status(400)
          .json({ message: "sessionCount must be a non-negative integer." });
      }
      updates.sessionCount = req.body.sessionCount;
    }

    if (req.body.status !== undefined) {
      const validStatuses = ["pending", "active", "completed", "cancelled"];
      if (!validStatuses.includes(req.body.status)) {
        return res.status(400).json({ message: "Invalid status value." });
      }
      updates.status = req.body.status;
    }

    // If no valid fields to update, return error
    if (Object.keys(updates).length === 0) {
      return res
        .status(400)
        .json({ message: "No valid fields provided for update." });
    }

    // Update the plan with only provided fields
    const updatedPlan = await Plans.findByIdAndUpdate(
      planId,
      { $set: updates },
      { new: true }
    );

    return res.status(200).json({
      message: "Plan updated successfully",
      data: updatedPlan,
    });
  } catch (error) {
    console.error("Edit Plan Error:", error);
    return res.status(500).json({
      message: "Failed to edit plan",
      error: error.message,
    });
  }
};

exports.getPlanByDoctorAndUser = async (req, res) => {
  try {
    const { userId } = req.params;
    const doctorId = req.user?.id; // Get the doctorId from the authenticated user
    // Validate that both doctorId and userId are provided
    if (!doctorId || !userId) {
      return res
        .status(400)
        .json({ message: "Doctor ID and User ID are required." });
    }

    // Find the plan by doctorId and userId
    const plan = await Plans.findOne({
      doctorId: doctorId,
      userId: userId,
    });

    // If no plan is found, return a 404 error
    if (!plan) {
      return res
        .status(404)
        .json({ message: "Plan not found for this doctor and user." });
    }

    // Return the found plan
    return res.status(200).json({
      message: "Plan retrieved successfully",
      data: plan,
    });
  } catch (error) {
    console.error("Get Plan Error:", error);
    return res.status(500).json({
      message: "Failed to get plan",
      error: error.message,
    });
  }
};

// Update appointment status (for post-session status changes)
exports.updateAppointmentStatus = async (req, res) => {
  const doctorId = req.user?.id;
  const { sessionId, status } = req.body;

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

  // Validate status
  const validStatuses = ["completed", "cancelled", "no-show"];
  if (!validStatuses.includes(status)) {
    return res.status(400).json({
      success: false,
      message: "Invalid status. Must be one of: completed, cancelled, no-show",
    });
  }

  try {
    const session = await Appointment.findOne({
      _id: sessionId,
    });

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

    // Ensure only the assigned doctor can update
    if (session.doctor.toString() !== doctorId) {
      return res.status(403).json({
        success: false,
        message: "Only the assigned doctor can update this appointment",
      });
    }

    // Update status
    session.status = status;
    await session.save();

    // Handle plan logic for completed sessions
    if (status === "completed") {
      const Plans = require("../../models/Plan");
      const plan = await Plans.findOne({
        userId: session.patient,
        doctorId: session.doctor,
      });

      if (plan) {
        if (plan.status === "active") {
          if (plan.unlockedSessions > 0) {
            plan.unlockedSessions -= 1;
            plan.completedSessions += 1;
            await plan.save();
          }
        } else if (plan.status === "pending") {
          plan.completedSessionsIndividual += 1;
          await plan.save();
        }
      }
    }

    // Notify patient
    const User = require("../../models/userModel");
    const sendMessage = require("../../utils/sendMessage");
    const patient = await User.findById(session.patient);
    if (patient) {
      const fullPhone = `${patient.countryCode}${patient.mobile}`;
      let message = "";

      switch (status) {
        case "completed":
          message = `Hi ${
            patient.fullname
          }, your session scheduled on ${new Date(
            session.date
          ).toLocaleDateString()} at ${
            session.timeSlot.startTime
          } has been completed. Thank you for attending!`;
          break;
        case "cancelled":
          message = `Hi ${
            patient.fullname
          }, your session scheduled on ${new Date(
            session.date
          ).toLocaleDateString()} at ${
            session.timeSlot.startTime
          } has been cancelled by the doctor.`;
          break;
        case "no-show":
          message = `Hi ${
            patient.fullname
          }, you were marked as no-show for your session scheduled on ${new Date(
            session.date
          ).toLocaleDateString()} at ${session.timeSlot.startTime}.`;
          break;
      }

      // await sendMessage(fullPhone, message, patient.email, patient._id);
    }

    return res.status(200).json({
      success: true,
      message: `Appointment status updated to ${status}`,
      data: session,
    });
  } catch (error) {
    console.error("Update appointment status error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};
