console.log("LECTURE ROUTE FILE LOADED");

const express = require("express")
const router = express.Router()
const Lecture = require("../../models/Lecture")
const mongoose = require("mongoose")

const requireAuth = require("../../middleware/requireAuth")
const courseAccess = require("../../middleware/courseAccess")

const Chapter = require("../../models/Chapter")
const Topic = require("../../models/Topic")

router.get("/lectures/:chapterId", requireAuth, async (req, res) => {
  try {
    const chapterId = req.params.chapterId
    const objId = new mongoose.Types.ObjectId(chapterId)

    const chapter = await Chapter.findById(chapterId)
    if (!chapter) {
      return res.status(404).json({ message: "Chapter not found" })
    }

    req.params.courseId = chapter.course

    let blocked = false
    await courseAccess(req, res, () => {
      blocked = true
    })

    if (!blocked) return

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

    const lectures = await Lecture.find({
      $or: [
        { chapterId: objId },
        { chapterId: chapterId },
        { chapter: objId },
        { chapter: chapterId }
      ],
      isActive: true
    }).sort({ order: 1 })

    res.json({
      locked: false,
      lectures: lectures
    })

  } catch (err) {
    console.error(err)
    res.status(500).json({ message: "Failed to fetch lectures" })
  }
})

router.get("/lectures/topic/:topicId", requireAuth, async (req, res) => {
  try {
    const topicId = req.params.topicId
    const objId = new mongoose.Types.ObjectId(topicId)

    console.log("TOPIC ID RECEIVED:", topicId);

    const lectures = await Lecture.find({
      topicId: objId,
      isActive: true
    }).sort({ order: 1 })

    console.log("LECTURES FOUND:", lectures.length);

    res.json({
      locked: false,
      lectures: lectures
    })

  } catch (err) {
    console.error(err)
    res.status(500).json({ message: "Failed to fetch topic lectures" })
  }
})

module.exports = router
