const Course = require("../models/Course")
const User = require("../models/User")

module.exports = async function courseAccess(req, res, next) {
  try {
    const user = req.user
    const courseId = req.params.courseId || req.params.id

    const course = await Course.findById(courseId)
    if (!course) {
      return res.status(404).json({ message: "Course not found" })
    }

    if (user?.role === "admin") {
      req.course = course
      return next()
    }

    if (course.isArchived || course.isFrozen || !course.isActive) {
      return res.status(403).json({ message: "Course unavailable" })
    }

    if (course.isPaid) {
      const dbUser = await User.findById(user._id)

      const purchased = dbUser.purchasedCourses.some(
        c => c.toString() === courseId
      )

      let inBatch = false

      if (dbUser.batch) {
        const batch = await require("../models/Batch")
          .findById(dbUser.batch)

        if (batch && batch.courses.includes(courseId)) {
          inBatch = true
        } 
      }

      req.hasAccess = purchased || inBatch
      next ()
    }

    req.course = course
    next()
  } catch (error) {
    res.status(500).json({ message: "Access check failed" })
  }
}
