/**
 * BackupNotificationLog Model
 *
 * One row per notification decision — sent, failed, or deliberately skipped.
 *
 * Skips are recorded as well as sends, following the same reasoning as
 * `FeatureRequestNotificationLog`: when an admin asks "why didn't I get an email
 * about last night's backup?", an empty log answers nothing, whereas a row
 * saying `skipped: true, skipReason: 'no recipients configured'` answers it
 * completely. The log doubles as the delivery-retry record.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type BackupNotificationType = 'success' | 'failure';

export interface IBackupNotificationLog extends Document {
  backupId: string;
  companyId: string;
  backupName: string;
  /** 'manual' | 'automatic' — copied from the backup so the log stands alone
   *  even after retention deletes the Backup document. */
  backupType: string;
  notificationType: BackupNotificationType;
  recipients: string[];
  subject: string;
  success: boolean;
  /** True when no email was attempted (disabled, no recipients, event muted). */
  skipped: boolean;
  skipReason?: string;
  /** Delivery attempts made, including the successful one. */
  attempts: number;
  messageId?: string;
  error?: string;
  createdAt: Date;
  updatedAt: Date;
}

const BackupNotificationLogSchema = new Schema<IBackupNotificationLog>({
  backupId: { type: String, required: true, index: true },
  companyId: { type: String, index: true },
  backupName: { type: String, trim: true, default: '' },
  backupType: { type: String, trim: true, default: 'manual' },
  notificationType: {
    type: String,
    enum: ['success', 'failure'],
    required: true,
    index: true,
  },
  recipients: [{ type: String, trim: true }],
  subject: { type: String, trim: true, default: '' },
  success: { type: Boolean, default: false, index: true },
  skipped: { type: Boolean, default: false },
  skipReason: { type: String, trim: true },
  attempts: { type: Number, default: 0 },
  messageId: { type: String, trim: true },
  error: { type: String, trim: true },
}, {
  timestamps: true,
});

BackupNotificationLogSchema.index({ createdAt: -1 });
BackupNotificationLogSchema.index({ companyId: 1, createdAt: -1 });
// One decision per backup per event type — the uniqueness that makes the
// duplicate-send guard in backupNotifications.ts reliable.
BackupNotificationLogSchema.index({ backupId: 1, notificationType: 1 });

// Match the AuditLog retention policy: one year, then MongoDB reclaims it.
BackupNotificationLogSchema.index({ createdAt: 1 }, { expireAfterSeconds: 365 * 24 * 60 * 60 });

export const BackupNotificationLog =
  mongoose.models.BackupNotificationLog ||
  mongoose.model<IBackupNotificationLog>('BackupNotificationLog', BackupNotificationLogSchema);
