/**
 * @ai-summary Core TypeScript types for the backup feature
 * @ai-context Defines interfaces for backup schedules, history, settings, and operations
 */

// ============================================
// Configuration Constants
// ============================================

export const BACKUP_CONFIG = {
  storagePath: process.env.BACKUP_STORAGE_PATH || '/app/data/backups',
  documentsPath: '/app/data/documents',
  tempPath: '/tmp/backup-work',
  maxFileSizeMB: 1024,
  archiveVersion: '1.0.0',
} as const;

export const CRON_EXPRESSIONS = {
  hourly: '0 * * * *',
  daily: '0 3 * * *',
  weekly: '0 3 * * 0',
  monthly: '0 3 1 * *',
} as const;

export const DEFAULT_RETENTION = {
  hourly: 24,
  daily: 7,
  weekly: 4,
  monthly: 12,
} as const;

/**
 * Tiered retention counts for unified classification system.
 * Each backup can belong to multiple categories; expiration is based on longest retention.
 */
export const TIERED_RETENTION = {
  hourly: 8,
  daily: 7,
  weekly: 4,
  monthly: 12,
} as const;

// ============================================
// Enums and Union Types
// ============================================

export type BackupFrequency = 'hourly' | 'daily' | 'weekly' | 'monthly';
export type BackupType = 'scheduled' | 'manual';
export type BackupStatus = 'in_progress' | 'completed' | 'failed';
export type BackupCategory = 'hourly' | 'daily' | 'weekly' | 'monthly';

// ============================================
// Database Entity Types
// ============================================

export interface BackupSchedule {
  id: string;
  name: string;
  frequency: BackupFrequency;
  cronExpression: string;
  retentionCount: number;
  isEnabled: boolean;
  lastRunAt: Date | null;
  nextRunAt: Date | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface BackupHistory {
  id: string;
  scheduleId: string | null;
  backupType: BackupType;
  filename: string;
  filePath: string;
  fileSizeBytes: number;
  databaseTablesCount: number | null;
  documentsCount: number | null;
  status: BackupStatus;
  errorMessage: string | null;
  startedAt: Date;
  completedAt: Date | null;
  createdBy: string | null;
  metadata: BackupMetadata;
  categories: BackupCategory[];
  expiresAt: Date | null;
}

export interface BackupSettings {
  id: string;
  settingKey: string;
  settingValue: string;
  updatedAt: Date;
}

// ============================================
// Archive Manifest Types
// ============================================

export interface BackupManifest {
  version: string;
  createdAt: string;
  applicationVersion: string;
  backupType: BackupType;
  scheduleName: string | null;
  contents: {
    database: {
      filename: string;
      tablesCount: number;
      postgresqlVersion: string;
      sizeBytes: number;
      checksum: string;
    };
    documents: {
      totalFiles: number;
      totalSizeBytes: number;
      usersCount: number;
    };
  };
  metadata: BackupMetadata;
}

export interface BackupMetadata {
  hostname?: string;
  createdBy?: string;
  compression?: string;
  postgresqlVersion?: string;
  [key: string]: string | number | boolean | undefined;
}

// ============================================
// API Request/Response Types
// ============================================

// List Backups
export interface ListBackupsParams {
  page?: number;
  pageSize?: number;
  status?: BackupStatus;
  backupType?: BackupType;
  sortBy?: 'startedAt' | 'fileSizeBytes' | 'status';
  sortOrder?: 'asc' | 'desc';
}

export interface ListBackupsResponse {
  items: BackupHistory[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// Create Backup
export interface CreateBackupRequest {
  name?: string;
  includeDocuments?: boolean;
}

export interface CreateBackupResponse {
  backupId: string;
  status: BackupStatus;
  message: string;
}

// Upload Backup
export interface UploadBackupResponse {
  backupId: string;
  filename: string;
  fileSizeBytes: number;
  message: string;
}

// Restore Preview
export interface RestorePreviewResponse {
  backupId: string;
  manifest: BackupManifest;
  warnings: string[];
  estimatedDuration: string;
}

// Restore Execute
export interface RestoreRequest {
  createSafetyBackup?: boolean;
}

export interface RestoreResponse {
  success: boolean;
  safetyBackupId?: string;
  restoredAt: string;
  message: string;
}

// Schedules
export interface CreateScheduleRequest {
  name: string;
  frequency: BackupFrequency;
  retentionCount?: number;
  isEnabled?: boolean;
}

export interface UpdateScheduleRequest {
  name?: string;
  frequency?: BackupFrequency;
  retentionCount?: number;
  isEnabled?: boolean;
}

export interface ScheduleResponse extends BackupSchedule {
  lastBackup?: BackupHistory | null;
}

// Settings
export interface BackupSettingsMap {
  emailOnSuccess: boolean;
  emailOnFailure: boolean;
  adminEmail: string;
  maxBackupSizeMb: number;
  compressionEnabled: boolean;
}

export interface UpdateSettingsRequest {
  emailOnSuccess?: boolean;
  emailOnFailure?: boolean;
  adminEmail?: string;
  maxBackupSizeMb?: number;
  compressionEnabled?: boolean;
}

// ============================================
// Service Operation Types
// ============================================

export interface CreateBackupOptions {
  name?: string;
  scheduleId?: string | null;
  backupType: BackupType;
  createdBy?: string | null;
  includeDocuments?: boolean;
}

export interface BackupResult {
  success: boolean;
  backupId: string;
  filePath?: string;
  error?: string;
}

export interface RestoreOptions {
  backupId: string;
  createSafetyBackup?: boolean;
}

export interface RestoreResult {
  success: boolean;
  safetyBackupId?: string;
  error?: string;
}

export interface RetentionCleanupResult {
  scheduleId: string;
  scheduleName: string;
  deletedCount: number;
  retainedCount: number;
  freedBytes: number;
}

// ============================================
// Job Types
// ============================================

export interface ScheduledBackupJobResult {
  processed: number;
  succeeded: number;
  failed: number;
  errors: Array<{ scheduleId: string; error: string }>;
}

export interface RetentionCleanupJobResult {
  processed: number;
  totalDeleted: number;
  totalFreedBytes: number;
  results: RetentionCleanupResult[];
  errors: Array<{ scheduleId: string; error: string }>;
}
