import mongoose, { Document, Schema } from 'mongoose';

export interface ICartItem {
  sku: mongoose.Types.ObjectId; // ProductSKU reference
  product: mongoose.Types.ObjectId; // Product reference
  quantity: number;
  price?: mongoose.Types.Decimal128;
  addedAt?: Date;
}

export interface ICart extends Document {
  user?: mongoose.Types.ObjectId | null; // optional, for guest carts
  items: ICartItem[];
  createdAt: Date;
  updatedAt: Date;
}

const CartItemSchema: Schema = new Schema({
  sku: { type: Schema.Types.ObjectId, ref: 'ProductSKU', required: true },
  product: { type: Schema.Types.ObjectId, ref: 'Product', required: true },
  quantity: { type: Number, required: true, min: 1, default: 1 },
  price: { type: Schema.Types.Decimal128 },
  addedAt: { type: Date, default: Date.now },
});

const CartSchema: Schema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: 'User', default: null },
   guestId: { type: String, default: null },
  items: { type: [CartItemSchema], default: [] },
}, { timestamps: true });

CartSchema.index({ user: 1 });
CartSchema.index({ guestId: 1 });

export default mongoose.models.Cart || mongoose.model<ICart>('Cart', CartSchema);