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

export interface IWishlist extends Document {
  _id: mongoose.Types.ObjectId;

  guest_id?: string;

  user_id?: mongoose.Types.ObjectId;

  product_id: mongoose.Types.ObjectId;

  createdAt: Date;
  
  updatedAt: Date;
}

const WishlistSchema = new Schema<IWishlist>(
  {
    guest_id: {
      type: String,
      trim: true,
      index: true,
      default: null,
    },

    user_id: {
      type: Schema.Types.ObjectId,
      ref: "User",
      index: true,
      default: null,
    },

    product_id: {
      type: Schema.Types.ObjectId,
      ref: "Product",
      required: [true, "Product is required"],
      index: true,
    },
  },
  {
    timestamps: true,
  }
);

// Indexes
WishlistSchema.index({ guest_id: 1 });
WishlistSchema.index({ user_id: 1 });
WishlistSchema.index({ product_id: 1 });

// Prevent duplicate products in wishlist
WishlistSchema.index(
  { user_id: 1, product_id: 1 },
  {
    unique: true,
    partialFilterExpression: {
      user_id: { $exists: true },
    },
  }
);

WishlistSchema.index(
  { guest_id: 1, product_id: 1 },
  {
    unique: true,
    partialFilterExpression: {
      guest_id: { $exists: true },
    },
  }
);

export default mongoose.models.Wishlist ||
  mongoose.model<IWishlist>("Wishlist", WishlistSchema);