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

const mongoose = require("mongoose")
const Subject = require("../../models/Subject")

// CREATE SUBJECT
router.post("/subjects", async (req, res) => {
  try {
    const { name, slug, classId } = req.body

    const subject = await Subject.create({
      name,
      slug,
      classId
    })

    res.status(201).json(subject)
  } catch (error) {
    res.status(500).json({
      message: "Failed to create subject",
      error: error.message
    })
  }
})

// GET ALL SUBJECTS
router.get("/subjects", async (req, res) => {
  try {
    const subjects = await Subject.find()
    res.json(subjects)
  } catch (error) {
    res.status(500).json({
      message: "Failed to fetch subjects",
      error: error.message
    })
  }
})

// GET SUBJECTS BY CLASS
router.get("/subjects/:classId", async (req, res) => {
  try {
    const { classId } = req.params

    if (!mongoose.Types.ObjectId.isValid(classId)) {
      return res.json([])
    }

    const subjects = await Subject.find({ classId })
    res.json(subjects)
  } catch (error) {
    res.status(500).json({
      message: "Failed to fetch subjects",
      error: error.message
    })
  }
})

module.exports = router
