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

// ─── Enums ───

export enum NotificationType {
    EMAIL = 'EMAIL',
    PUSH = 'PUSH',
    SMS = 'SMS',
    WHATSAPP = 'WHATSAPP'
}

export enum NotificationPurpose {
    // Reminders (scheduled via delay queue)
    APPOINTMENT_REMINDER_24H = 'APPOINTMENT_REMINDER_24H',
    APPOINTMENT_REMINDER_4H = 'APPOINTMENT_REMINDER_4H',
    APPOINTMENT_REMINDER_2H = 'APPOINTMENT_REMINDER_2H',
    APPOINTMENT_REMINDER_AT_TIME = 'APPOINTMENT_REMINDER_AT_TIME',
    // Immediate notifications
    APPOINTMENT_CONFIRMATION = 'APPOINTMENT_CONFIRMATION',
    APPOINTMENT_CANCELLATION = 'APPOINTMENT_CANCELLATION',
    APPOINTMENT_RESCHEDULED = 'APPOINTMENT_RESCHEDULED',
    APPOINTMENT_COMPLETED = 'APPOINTMENT_COMPLETED',
    // Other
    SUBSCRIPTION_CONFIRMATION = 'SUBSCRIPTION_CONFIRMATION'
}

export enum NotificationStatus {
    PENDING = 'PENDING',
    SENT = 'SENT',
    FAILED = 'FAILED',
    SKIPPED = 'SKIPPED'
}

// ─── Interface ───

export interface INotificationLog extends Document {
    appointmentId?: mongoose.Types.ObjectId;
    userId: mongoose.Types.ObjectId;
    jobId: string;
    type: NotificationType;
    purpose: NotificationPurpose;
    status: NotificationStatus;
    sentAt?: Date;
    metadata?: Record<string, any>;
    error?: string;
    idempotencyKey: string;  // Unique: appointmentId-purpose-type-version
    createdAt: Date;
    updatedAt: Date;
}

// ─── Schema ───

const NotificationLogSchema = new Schema<INotificationLog>({
    appointmentId: { type: Schema.Types.ObjectId, ref: 'Appointment' },
    userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
    jobId: { type: String, required: true },
    type: { type: String, enum: Object.values(NotificationType), required: true },
    purpose: { type: String, enum: Object.values(NotificationPurpose), required: true },
    status: { type: String, enum: Object.values(NotificationStatus), default: NotificationStatus.PENDING },
    sentAt: { type: Date },
    metadata: { type: Schema.Types.Mixed },
    error: { type: String },
    idempotencyKey: { type: String, required: true, unique: true, index: true }
}, {
    timestamps: true
});

// Compound index for efficient lookups
NotificationLogSchema.index({ appointmentId: 1, purpose: 1, type: 1 });
NotificationLogSchema.index({ userId: 1, status: 1 });

export default mongoose.model<INotificationLog>('NotificationLog', NotificationLogSchema);
