const express = require("express");
const requireUser = require("../../middleware/requireUser");
const router = express.Router();
const Chapter = require("../../models/Chapter");
const Course = require("../../models/Course")

router.post("/chapters", async (req, res) => {
  try {
    const { title, course, order, isFreePreview } = req.body;

    const chapter = await Chapter.create({
      title,
      course,
      order,
      isFreePreview
    });

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

router.get("/courses/:courseId/chapters", async (req, res) => {
  const chapters = await Chapter.find({
    course: req.params.courseId
  }).sort({ order: 1 })

  res.json(chapters)
})

router.post("/courses/:courseId/chapters", async (req, res) => {
  const { title, order, isFreePreview } = req.body

  const chapter = await Chapter.create({
    title,
    course: req.params.courseId,
    order,
    isFreePreview
  })

  res.status(201).json(chapter)
})

router.get("/chapters/:courseId", requireUser, async (req, res) => {
  try{
    const course = await Course.findById(req.params.courseId);

    if (!course){
      return res.status(404).json({
        message:"Course not found"
      })
    }

    const chapter = await Chapter.find({
      course: req.params.courseId,
    }).sort({order:1});

    res.json({
      frozen: false,
      chapter
    })
  } catch(error){
    res.status(500).json({
      message:"Failed to fetch chapters",
    });
   }
});

router.get("/chapters/single/:id", async (req, res) => {
  try {
    const chapter = await Chapter.findById(req.params.id)

    if (!chapter) {
      return res.status(404).json({
        message: "Chapter not found"
      })
    }

    res.json(chapter)
  } catch (error) {
    res.status(500).json({
      message: "Failed to fetch chapter",
      error: error.message
    })
  }
})

router.put("/chapters/:id", async (req, res) => {
  try {
    const { title } = req.body

    const chapter = await Chapter.findByIdAndUpdate(
      req.params.id,
      { title },
      { new: true }
    )

    if (!chapter) {
      return res.status(404).json({ message: "Chapter not found" })
    }

    res.json(chapter)
  } catch (error) {
    res.status(500).json({
      message: "Failed to update chapter",
      error: error.message
    })
  }
})

module.exports = router;
