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

// ─── Enums ───

export enum NotificationCategory {
    APPOINTMENT = 'APPOINTMENT',
    PRESCRIPTION = 'PRESCRIPTION',
    PAYMENT = 'PAYMENT',
    SUBSCRIPTION = 'SUBSCRIPTION',
    SYSTEM = 'SYSTEM'
}

export enum NotificationAction {
    APPOINTMENT_BOOKED = 'APPOINTMENT_BOOKED',
    APPOINTMENT_CONFIRMED = 'APPOINTMENT_CONFIRMED',
    APPOINTMENT_CANCELLED = 'APPOINTMENT_CANCELLED',
    APPOINTMENT_RESCHEDULED = 'APPOINTMENT_RESCHEDULED',
    APPOINTMENT_REMINDER = 'APPOINTMENT_REMINDER',
    PRESCRIPTION_ISSUED = 'PRESCRIPTION_ISSUED',
    PRESCRIPTION_READY = 'PRESCRIPTION_READY',
    PAYMENT_RECEIVED = 'PAYMENT_RECEIVED',
    PAYMENT_FAILED = 'PAYMENT_FAILED',
    SUBSCRIPTION_ACTIVATED = 'SUBSCRIPTION_ACTIVATED',
    SUBSCRIPTION_EXPIRES = 'SUBSCRIPTION_EXPIRES',
    SUBSCRIPTION_RENEWAL = 'SUBSCRIPTION_RENEWAL',
    MESSAGE_RECEIVED = 'MESSAGE_RECEIVED',
    OTHER = 'OTHER'
}

// ─── Interface ───

export interface INotification extends Document {
    userId: mongoose.Types.ObjectId;
    title: string;
    message: string;
    category: NotificationCategory;
    action: NotificationAction;
    isRead: boolean;
    readAt?: Date;
    referenceId?: mongoose.Types.ObjectId; // appointmentId, prescriptionId, etc.
    referenceType?: string; // 'Appointment', 'Prescription', etc.
    actionUrl?: string; // URL to navigate when clicked
    metadata?: Record<string, any>;
    priority: 'low' | 'medium' | 'high';
    createdAt: Date;
    updatedAt: Date;
}

// ─── Schema ───

const NotificationSchema = new Schema<INotification>({
    userId: { 
        type: Schema.Types.ObjectId, 
        ref: 'User', 
        required: true,
        index: true
    },
    title: { 
        type: String, 
        required: true 
    },
    message: { 
        type: String, 
        required: true 
    },
    category: { 
        type: String, 
        enum: Object.values(NotificationCategory), 
        required: true,
        index: true
    },
    action: { 
        type: String, 
        enum: Object.values(NotificationAction), 
        required: true 
    },
    isRead: { 
        type: Boolean, 
        default: false,
        index: true
    },
    readAt: { 
        type: Date 
    },
    referenceId: { 
        type: Schema.Types.ObjectId 
    },
    referenceType: { 
        type: String
    },
    actionUrl: { 
        type: String 
    },
    metadata: { 
        type: Schema.Types.Mixed 
    },
    priority: { 
        type: String, 
        enum: ['low', 'medium', 'high'],
        default: 'medium'
    }
}, {
    timestamps: true
});

// Compound indexes for efficient queries
NotificationSchema.index({ userId: 1, isRead: 1, createdAt: -1 });
NotificationSchema.index({ userId: 1, category: 1, createdAt: -1 });
NotificationSchema.index({ userId: 1, createdAt: -1 });

export default mongoose.model<INotification>('Notification', NotificationSchema);
