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

export interface IAppointment extends Document {
  patientId: mongoose.Types.ObjectId;
  doctorId: mongoose.Types.ObjectId;
  appointmentDate: Date;
  durationMinutes: number;
  status: 'Scheduled' | 'Completed' | 'Cancelled';
  confirmationStatus: 'Pending' | 'Confirmed' | 'Declined';
  reasonForVisit?: string;
  notes?: string;
  remindersSent: {
    email: boolean;
    sms: boolean;
    whatsapp: boolean;
  };
  scheduledJobIds: string[];       // BullMQ job IDs for active delayed jobs
  notificationVersion: number;     // Incremented on reschedule to invalidate old jobs
  createdAt: Date;
  updatedAt: Date;
}

const appointmentSchema = new Schema<IAppointment>({
  patientId: {
    type: Schema.Types.ObjectId,
    ref: 'Patient',
    required: true
  },
  doctorId: {
    type: Schema.Types.ObjectId,
    ref: 'Doctor',
    required: true
  },
  appointmentDate: {
    type: Date,
    required: true
  },
  durationMinutes: {
    type: Number,
    default: 30
  },
  status: {
    type: String,
    enum: ['Scheduled', 'Completed', 'Cancelled'],
    default: 'Scheduled'
  },
  confirmationStatus: {
    type: String,
    enum: ['Pending', 'Confirmed', 'Declined'],
    default: 'Pending'
  },
  reasonForVisit: String,
  notes: String,
  remindersSent: {
    email: { type: Boolean, default: false },
    sms: { type: Boolean, default: false },
    whatsapp: { type: Boolean, default: false }
  },
  // ─── Notification tracking ───
  scheduledJobIds: {
    type: [String],
    default: []
  },
  notificationVersion: {
    type: Number,
    default: 1
  }
}, { timestamps: true });

// Index for efficient queries
appointmentSchema.index({ patientId: 1, appointmentDate: 1 });
appointmentSchema.index({ doctorId: 1, appointmentDate: 1 });
appointmentSchema.index({ status: 1 });

export default mongoose.model<IAppointment>('Appointment', appointmentSchema);
