// backend/middlewares/enrollment.middleware.js
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

exports.requireEnrollment = (options = {}) => {
  // options: { allowTeacher: true } - teachers unaffected
  return async (req, res, next) => {
    try {
      // allow admins and teachers to bypass if option present
      if (req.user?.role === "admin") return next();
      if (options.allowTeacher && req.user?.role === "teacher") return next();

      // student must be logged in
      if (!req.user || !req.user.id) {
        return res.status(401).json({ message: "Unauthorized" });
      }

      const subjectId = Number(
        req.params?.subjectId || req.body?.subjectId || req.query?.subjectId
      );

      if (!subjectId && req.params.lessonId) {
        const lesson = await prisma.lesson.findUnique({
          where: { id: Number(req.params.lessonId) },
          select: { subjectId: true },
        });
        if (lesson) subjectId = lesson.subjectId;
      }

      // if subjectId missing — we can't verify; deny
      if (!subjectId || isNaN(subjectId)) {
        return res
          .status(400)
          .json({ message: "subjectId required for enrollment check" });
      }

      const enrollment = await prisma.enrollment.findUnique({
        where: { studentId_subjectId: { studentId: req.user.id, subjectId } },
      });

      if (!enrollment) {
        return res
          .status(403)
          .json({ message: "You are not enrolled in this subject" });
      }

      // check expiry
      if (enrollment.expiresAt && new Date(enrollment.expiresAt) < new Date()) {
        return res.status(403).json({ message: "Your enrollment has expired" });
      }

      // ok
      req.enrollment = enrollment;
      next();
    } catch (err) {
      console.error("Enrollment check error:", err);
      return res.status(500).json({ message: "Server error" });
    }
  };
};
