const mongoose = require('mongoose');

const notificationSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, 'User ID is required']
  },
  title: {
    type: String,
    required: [true, 'Notification title is required'],
    trim: true
  },
  message: {
    type: String,
    required: [true, 'Notification message is required'],
    trim: true
  },
  type: {
    type: String,
    enum: ['info', 'success', 'warning', 'error', 'order', 'promotion'],
    default: 'info'
  },
  read: {
    type: Boolean,
    default: false
  },
  action: {
    type: String,
    trim: true
  },
  actionData: {
    type: mongoose.Schema.Types.Mixed
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Index for faster querying
notificationSchema.index({ user: 1, read: 1, createdAt: -1 });

// Static method to create a new notification
notificationSchema.statics.createNotification = async function(userId, notificationData) {
  const notification = new this({
    user: userId,
    ...notificationData
  });
  
  return await notification.save();
};

// Static method to get unread count
notificationSchema.statics.getUnreadCount = async function(userId) {
  return await this.countDocuments({ 
    user: userId, 
    read: false 
  });
};

const Notification = mongoose.model('Notification', notificationSchema);

module.exports = Notification;
