/**
 * BackupSettings Model
 *
 * Per-company backup configuration: frequency, schedule, scope, retention,
 * notifications. A company can only have one BackupSettings document
 * (enforced by unique index on companyId).
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IBackupSettings extends Document {
  companyId: string;
  enabled: boolean;
  frequency: 'daily' | 'weekly' | 'monthly' | 'yearly' | 'custom';
  customIntervalDays?: number;
  time: string;                       // HH:mm format (e.g., "02:30")
  timezone: string;                   // IANA timezone (e.g., "Asia/Kolkata")
  keepCount: number;                  // Number of backups to retain
  notifyOnComplete: boolean;
  /**
   * @deprecated Kept so existing configurations keep working. New addresses go
   * into `notifyEmails`; the notification service reads both and de-duplicates.
   */
  notifyEmail?: string;
  /** Company-level recipients, unioned with the platform-wide list. */
  notifyEmails: string[];
  autoDeleteAfter: '7d' | '15d' | '30d' | '90d' | '6mo' | '1yr' | 'never';
  scope: 'everything' | 'custom';
  categories: string[];
  encrypted: boolean;
  lastBackupAt?: Date;
  nextBackupAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const BackupSettingsSchema = new Schema<IBackupSettings>({
  companyId: {
    type: String,
    required: true,
    unique: true,
    index: true,
  },
  enabled: {
    type: Boolean,
    default: false,
  },
  frequency: {
    type: String,
    enum: ['daily', 'weekly', 'monthly', 'yearly', 'custom'],
    default: 'daily',
  },
  customIntervalDays: {
    type: Number,
    min: 1,
  },
  time: {
    type: String,
    default: '02:00',
  },
  timezone: {
    type: String,
    default: 'UTC',
  },
  keepCount: {
    type: Number,
    default: 5,
    min: 1,
  },
  notifyOnComplete: {
    type: Boolean,
    default: true,
  },
  notifyEmail: {
    type: String,
    trim: true,
    lowercase: true,
  },
  notifyEmails: [{
    type: String,
    trim: true,
    lowercase: true,
  }],
  autoDeleteAfter: {
    type: String,
    enum: ['7d', '15d', '30d', '90d', '6mo', '1yr', 'never'],
    default: 'never',
  },
  scope: {
    type: String,
    enum: ['everything', 'custom'],
    default: 'everything',
  },
  categories: [{
    type: String,
    trim: true,
  }],
  encrypted: {
    type: Boolean,
    default: false,
  },
  lastBackupAt: {
    type: Date,
  },
  nextBackupAt: {
    type: Date,
  },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true },
});

export const BackupSettings = mongoose.models.BackupSettings || mongoose.model<IBackupSettings>('BackupSettings', BackupSettingsSchema);