// models/Favorite.js - Improved Version
import mongoose from "mongoose";

const favoriteSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true  // Index for faster queries
  },
  itemType: {
    type: String,
    required: true,
    enum: ['nominee', 'directory', 'ai']
  },
  // Store all possible references
  nomineeWebsite: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'WebsiteSubmission',
    index: true  // Index for faster lookups
  },
  directory: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'SubmitDirectory',
    index: true  // Index for faster lookups
  },
  aiWebsite: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'SubmitAiWebsite',
    index: true  // Index for faster lookups
  },
  
 }, { timestamps: true } 
);

// Compound indexes with partial filter to prevent duplicate favorites
// Only applies index when the field is not null
favoriteSchema.index(
  { user: 1, nomineeWebsite: 1 }, 
  { 
    unique: true, 
    partialFilterExpression: { nomineeWebsite: { $type: 'objectId' } }
  }
);

favoriteSchema.index(
  { user: 1, directory: 1 }, 
  { 
    unique: true, 
    partialFilterExpression: { directory: { $type: 'objectId' } }
  }
);

favoriteSchema.index(
  { user: 1, aiWebsite: 1 }, 
  { 
    unique: true, 
    partialFilterExpression: { aiWebsite: { $type: 'objectId' } }
  }
);

// Index for sorting by creation date
favoriteSchema.index({ createdAt: -1 });

const Favorite = mongoose.model("Favorite", favoriteSchema);
export default Favorite

