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

router.get("/courses/public", async (req, res) => {
  try {
    const { class: userClass, goal,} = req.query;

    const filter ={
      isFrozen: false,
      isActive: true,
      isArchived: false
    };

    if (userClass) {
      filter.class = userClass;
    }

    if (goal) {
      filter.$or = [
        { goal: goal },
        { goal: "CBSE" },
        { goal: { $exists: false } }
      ];
    }

    const courses = await Course.find(filter)
    .select("name description isPaid price thumbnail class goal");

    console.log("FILTER:", filter);
    console.log("COURSES FOUND:", courses.length);

    res.json(courses)

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

router.get("/courses/my", requireAuth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id)

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

    let courses = []

    if (user.batch) {
      const batch = await Batch.findById(user.batch).populate({
        path: "courses",
        match: {
          isFrozen: false,
          isActive: true,
          isArchived: false
        },
        select: "name description isPaid price thumbnail class"
      })

      if (batch) {
        courses = [...batch.courses]
      }
    }

    if (user.purchasedCourses && user.purchasedCourses.length > 0) {
      const purchased = await Course.find({
        _id: { $in: user.purchasedCourses }
      })

      const map = new Map()

      courses.forEach(c => map.set(c._id.toString(), c))
      purchased.forEach(c => map.set(c._id.toString(), c))

      courses = Array.from(map.values())
    }

    res.json(courses)

  } catch (error) {
    console.error("MY COURSES ERROR ->", error)
    res.status(500).json({
      message: "Failed to fetch courses",
      error: error.message
    })
  }
})

router.get("/courses/:id", async (req, res) => {
  console.log("COURSE ROUTE HIT")

  try {
    const course = await Course.findOne({
      _id: req.params.id,
      isFrozen: false,
      isActive: true,
      isArchived: false
    })

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

      return res.json({
        ...course.toObject(),
        locked: course.isPaid === true
      });    

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

router.put("/update-preferences", requireAuth, async (req, res) => {
  try {
    const userId = req.user.id;

    const { class: userClass, goal, stream } = req.body;

    const updatedUser = await User.findByIdAndUpdate(
      userId,
      {
        class: userClass,
        goal,
        stream,
        profileCompleted: true
      },
      { new: true }
    );

    res.json({
      message: "Preferences updated successfully",
      user: updatedUser
    });

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

module.exports = router
