const Cart = require("../models/cartModel");
const Course = require("../models/courseModel");

// --- GET CART ---
exports.getMyCart = async (req, res) => {
  try {
    let cart = await Cart.findOne({ user: req.user.id });

    // If no cart exists yet, return empty structure
    if (!cart) {
      return res.status(200).json({
        status: "success",
        results: 0,
        data: { items: [], totalPrice: 0 },
      });
    }

    res.status(200).json({
      status: "success",
      results: cart.items.length,
      data: {
        items: cart.items,
        totalPrice: cart.totalPrice, // Uses the virtual field
      },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// --- ADD TO CART ---
exports.addToCart = async (req, res) => {
  try {
    const { courseId } = req.body;

    // 1. Check if Course Exists & Get Details (Snapshotting)
    const course = await Course.findById(courseId);
    if (!course) {
      return res
        .status(404)
        .json({ status: "fail", message: "Course not found" });
    }

    // 2. Find User's Cart or Create New One
    let cart = await Cart.findOne({ user: req.user.id });
    if (!cart) {
      cart = await Cart.create({ user: req.user.id, items: [] });
    }

    // 3. Check if Item already in cart
    const isExists = cart.items.some(
      (item) => item.course.toString() === courseId
    );

    if (isExists) {
      return res
        .status(400)
        .json({ status: "fail", message: "Course already in cart" });
    }

    // 4. 🚀 EMBEDDING: Push the snapshot object
    // Note: We handle the instructor name safely (it might be an object or string in your Course model)
    const instructorName =
      typeof course.instructors[0] === "object"
        ? course.instructors[0]?.name
        : "Unknown Instructor";

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

    await cart.save();

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

// --- REMOVE FROM CART ---
exports.removeFromCart = async (req, res) => {
  try {
    const { courseId } = req.params;

    const cart = await Cart.findOne({ user: req.user.id });
    if (!cart) {
      return res
        .status(404)
        .json({ status: "fail", message: "Cart not found" });
    }

    // Filter out the item
    cart.items = cart.items.filter(
      (item) => item.course.toString() !== courseId
    );
    await cart.save();

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

// --- CLEAR CART ---
exports.clearCart = async (req, res) => {
  try {
    await Cart.findOneAndDelete({ user: req.user.id });
    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
