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

// CREATE TOPIC (ADMIN)
router.post("/topics", requireAdmin, async (req, res) => {
  try {
    const { title, chapterId, order } = req.body

    const topic = await Topic.create({
      title,
      chapterId,
      order
    })

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

// GET TOPICS BY CHAPTER (ADMIN)
router.get("/topics/:chapterId", requireAdmin, async (req, res) => {
  try {
    const topics = await Topic.find({
      chapterId: req.params.chapterId
    }).sort({ order: 1 })

    res.json(topics)
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// GET TOPICS BY CHAPTER (USER)
router.get("/user/topics/:chapterId", requireUser, async (req, res) => {
  try {
    const topics = await Topic.find({
      chapterId: req.params.chapterId,
      isActive: true
    }).sort({ order: 1 })

    res.json(topics)
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// DELETE TOPIC
router.delete("/topics/:id", requireAdmin, async (req, res) => {
  try {
    await Topic.findByIdAndDelete(req.params.id)
    res.json({ message: "Topic deleted" })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

module.exports = router