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

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

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

    if (course.isArchived) {
      return res.status(404).json({ message: "Course not available" });
    }

    if (!req.hasAccess && course.isPaid) {
      return res.status(200).json({
        locked: true,
        message: "Contact admin to unlock this course",
        chapters: []
      })
    }

    if (course.isContentLocked) {
      return res.status(423).json({
        frozen: true,
        message: "Course content is locked"
      });
    }

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

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

module.exports = router;
