const Wishlist = require("../models/wishlistModel");
const Course = require("../models/courseModel");

exports.getMyWishlist = async (req, res) => {
  try {
    const wishlist = await Wishlist.findOne({ user: req.user.id });
    const items = wishlist ? wishlist.items : [];

    res.status(200).json({
      status: "success",
      results: items.length,
      data: { items },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.addToWishlist = async (req, res) => {
  try {
    const { courseId } = req.body;

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

    let wishlist = await Wishlist.findOne({ user: req.user.id });
    if (!wishlist) {
      wishlist = await Wishlist.create({ user: req.user.id, items: [] });
    }

    const isExists = wishlist.items.some(
      (item) => item.course.toString() === courseId
    );
    if (isExists) {
      return res.status(400).json({ message: "Course already in wishlist" });
    }

    // 🚀 Embed snapshot
    const instructorName =
      typeof course.instructors[0] === "object"
        ? course.instructors[0]?.name
        : "Unknown Instructor";

    wishlist.items.push({
      course: course._id,
      name: course.name,
      coverImage: course.coverImage,
      price: course.price,
      instructorName: instructorName,
    });

    await wishlist.save();

    res
      .status(200)
      .json({ status: "success", data: { items: wishlist.items } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.removeFromWishlist = async (req, res) => {
  try {
    const wishlist = await Wishlist.findOne({ user: req.user.id });
    if (!wishlist)
      return res.status(404).json({ message: "Wishlist not found" });

    wishlist.items = wishlist.items.filter(
      (item) => item.course.toString() !== req.params.courseId
    );
    await wishlist.save();

    res
      .status(200)
      .json({ status: "success", data: { items: wishlist.items } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
