import "server-only"; import mongoose, { Schema, type Model } from "mongoose"; export const EVENT_TYPES = [ "request.received", "request.accepted", "request.rejected", "invite.received", "invite.responded", "request.withdrawn", "team.updated", "team.disbanded", "member.left", "member.removed", "leadership.transferred", "message.received", ] as const; export type EventType = (typeof EVENT_TYPES)[number]; export interface NotificationDoc { _id: mongoose.Types.ObjectId; userId: string; type: EventType; data: Record; readAt: Date | null; eventId: string; createdAt: Date; updatedAt: Date; } const NotificationSchema = new Schema( { userId: { type: String, required: true, index: true }, type: { type: String, enum: EVENT_TYPES, required: true }, data: { type: Schema.Types.Mixed, default: () => ({}) }, readAt: { type: Date, default: null, index: true }, eventId: { type: String, required: true, unique: true }, }, { timestamps: true, } ); // TTL index: auto-delete notifications after 30 days NotificationSchema.index({ createdAt: 1 }, { expireAfterSeconds: 30 * 24 * 60 * 60 }); // Compound index for fast queries: user's unread / chronological list NotificationSchema.index({ userId: 1, readAt: 1, createdAt: -1 }); export const Notification: Model = (mongoose.models.Notification as Model) || mongoose.model("Notification", NotificationSchema);