const express = require("express")
const router = express.Router()
const Enrollment = require("../../models/Enrollment")
const requireAdmin = require("../../middleware/requireAdmin")

router.post("/enroll", requireAdmin, async (req, res) => {
  try {
    if (req.user.role !== "admin") {
      return res.status(403).json({ message: "Admin only" })
    }

    const { userId, courseId } = req.body

    const exists = await Enrollment.findOne({ user: userId, course: courseId })
    if (exists) {
      return res.status(400).json({ message: "User already enrolled" })
    }

    const enrollment = await Enrollment.create({
      user: userId,
      course: courseId,
      status: "active"
    })

    res.status(201).json(enrollment)
  } catch (error) {
    res.status(500).json({ message: "Enrollment failed" })
  }
})

module.exports = router
