import mongoose, { Schema, Document } from 'mongoose';

export interface IAlertDocument extends Document {
  // _id is handled by Mongoose
  type: 'LowStock' | 'PMSchedule' | 'TicketSLA' | 'System' | 'VCOMAlarm';
  message: string;
  severity: 'Info' | 'Warning' | 'Critical';
  createdAt: Date;
  isRead: boolean;
  link?: string;
  userId?: mongoose.Types.ObjectId; // For user-specific alerts
  createdAt_field: Date;
  // VCOM Alarm specific fields
  vcomAlarmId?: number; // Alarm ID from VCOM API
  systemKey?: string; // System key from VCOM
  alarmType?: string; // Alarm type (total-outage, misproduction, etc.)
  componentId?: string; // Component ID
  componentType?: string; // Component type (inverter, system, etc.)
  componentName?: string; // Component name
  startedAt?: Date; // When alarm started
  duration?: string; // ISO-8601 duration
  affectedPower?: number; // Affected power in percent
  losses?: number; // Estimated losses in kWh
  ticketId?: number; // Associated ticket ID from VCOM
}

const alertSchema = new Schema<IAlertDocument>(
  {
    type: {
      type: String,
      enum: ['LowStock', 'PMSchedule', 'TicketSLA', 'System', 'VCOMAlarm'],
      required: true,
    },
    message: { type: String, required: true },
    severity: {
      type: String,
      enum: ['Info', 'Warning', 'Critical'],
      default: 'Info',
    },
    isRead: { type: Boolean, default: false },
    link: String,
    userId: { type: Schema.Types.ObjectId, ref: 'User' },
    createdAt: { type: Date, default: Date.now },
    // VCOM Alarm specific fields
    vcomAlarmId: Number,
    systemKey: String,
    alarmType: String,
    componentId: String,
    componentType: String,
    componentName: String,
    startedAt: Date,
    duration: String,
    affectedPower: Number,
    losses: Number,
    ticketId: Number,
  },
  {
    timestamps: true,
  }
);

alertSchema.index({ userId: 1, isRead: 1 });
alertSchema.index({ type: 1 });
alertSchema.index({ severity: 1 });
alertSchema.index({ createdAt: -1 });
alertSchema.index({ isRead: 1 });
alertSchema.index({ vcomAlarmId: 1 }); // For VCOM alarms
alertSchema.index({ systemKey: 1 }); // For VCOM alarms

export const Alert = mongoose.model<IAlertDocument>('Alert', alertSchema);
