const prisma = require("../lib/prisma");

exports.canSendNotification = async (req, res, next) => {
  const { role, id } = req.user;
  const { targetUserId } = req.body;

  // Students can never send
  if (role === "student") {
    return res.status(403).json({ message: "Students cannot send notifications" });
  }

  // Admin & accountant can send to anyone
  if (role === "admin" || role === "accountant") {
    return next();
  }

  // Teacher: only to their students
  if (role === "teacher") {
    const isStudentOfTeacher = await prisma.enrollment.findFirst({
      where: {
        studentId: targetUserId,
        subject: {
          teacherId: id,
        },
      },
    });

    if (!isStudentOfTeacher) {
      return res.status(403).json({
        message: "Teachers can only notify their students",
      });
    }

    return next();
  }

  return res.status(403).json({ message: "Access denied" });
};
