const mongoose = require("mongoose");
const { v4: uuidv4 } = require("uuid");

const cartItemSchema = new mongoose.Schema({
  product: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Product",
    required: true,
  },
  quantity: {
    type: Number,
    required: true,
    min: [1, "Quantity must be at least 1"],
    default: 1,
  },
  color: { type: String },
  size: { type: String, enum: ["S", "M", "L", "XL", "XXL"] },
  price: { type: Number, required: true },
});

const cartSchema = new mongoose.Schema(
  {
    sessionId: {
      type: String,
      default: () => uuidv4(), // ✅ give unique id for guests
      index: true,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      default: null,
      index: true,
    },
    items: [cartItemSchema],
    totalPrice: { type: Number, default: 0 },
    totalItems: { type: Number, default: 0 },
  },
  { timestamps: true }
);

// Remove wrong unique constraint (important!)
cartSchema.index({ sessionId: 1 });
cartSchema.index({ user: 1 });

// Auto-calc totals before save
cartSchema.pre("save", function (next) {
  this.totalItems = this.items.reduce((t, i) => t + i.quantity, 0);
  this.totalPrice = this.items.reduce((t, i) => t + i.price * i.quantity, 0);
  next();
});

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