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

export type NotificationType =
  | 'QUIZ_PUBLISHED'
  | 'QUIZ_REMINDER'
  | 'QUIZ_ENDING_SOON'
  | 'QUIZ_RESULT'
  | 'ATTENDANCE_STREAK'
  | 'CERTIFICATE_APPROVED'
  | 'CERTIFICATE_REJECTED'
  | 'ATTENDANCE_REMINDER'
  | 'REWARD'
  | 'GENERAL';


export interface INotificationDocument extends Document {
  user: Types.ObjectId;
  title: string;
  message: string;
  type: NotificationType;
  isRead: boolean;
  eventKey?: string;
  meta?: Record<string, unknown>;
  createdAt: Date;
  updatedAt: Date;
}

const notificationSchema = new Schema<INotificationDocument>(
  {
    user: { type: Schema.Types.ObjectId, ref: 'User', required: true, index: true },
    title: { type: String, required: true, trim: true },
    message: { type: String, required: true, trim: true },
    type: {
      type: String,
      enum: [
        'QUIZ_PUBLISHED',
        'QUIZ_REMINDER',
        'QUIZ_ENDING_SOON',
        'QUIZ_RESULT',
        'ATTENDANCE_STREAK',
        'CERTIFICATE_APPROVED',
        'CERTIFICATE_REJECTED',
        'ATTENDANCE_REMINDER',
        'REWARD',
        'GENERAL',
      ],
      required: true,
    },
    isRead: { type: Boolean, default: false },
    eventKey: { type: String, required: false },
    // route removed for decoupling
    meta: { type: Object, required: false },
  },
  { timestamps: true },
);

// Auto-delete after 30 days.
notificationSchema.index({ createdAt: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 30 });

// Deduplicate notification events per user.
notificationSchema.index({ user: 1, eventKey: 1 }, { unique: true, sparse: true });

export default mongoose.model<INotificationDocument>('Notification', notificationSchema);
