const mongoose = require("mongoose");

const cartSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.ObjectId,
      ref: "User",
      required: [true, "Cart must belong to a user"],
      unique: true, // One cart per user
    },
    items: [
      {
        course: {
          type: mongoose.Schema.ObjectId,
          ref: "Course",
          required: true,
        },
        // 🚀 SNAPSHOT DATA (Fast Read)
        name: String,
        coverImage: String,
        price: Number,
        instructorName: String,
      },
    ],
    updatedAt: {
      type: Date,
      default: Date.now,
    },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

// Virtual: Calculate Total Price on the fly
cartSchema.virtual("totalPrice").get(function () {
  if (!this.items) return 0;
  return this.items.reduce((total, item) => total + item.price, 0);
});

const Cart = mongoose.model("Cart", cartSchema);
module.exports = Cart;
