/**
 * @ai-summary Job for backup retention cleanup
 * @ai-context Runs daily at 4 AM to enforce retention policies
 */

import { Pool } from 'pg';
import { logger } from '../../../core/logging/logger';
import { BackupRetentionService } from '../domain/backup-retention.service';
import { RetentionCleanupJobResult } from '../domain/backup.types';

let pool: Pool | null = null;

/**
 * Sets the database pool for the job
 */
export function setBackupCleanupJobPool(dbPool: Pool): void {
  pool = dbPool;
}

/**
 * Processes backup retention cleanup for all schedules
 */
export async function processBackupRetention(): Promise<RetentionCleanupJobResult> {
  if (!pool) {
    throw new Error('Database pool not initialized for backup cleanup job');
  }

  const retentionService = new BackupRetentionService(pool);

  try {
    logger.info('Starting backup retention cleanup job');

    const result = await retentionService.processRetentionCleanup();

    // Also cleanup failed backups
    const failedCount = await retentionService.cleanupFailedBackups();

    logger.info('Backup retention cleanup job completed', {
      schedulesProcessed: result.processed,
      totalDeleted: result.totalDeleted + failedCount,
      totalFreedBytes: result.totalFreedBytes,
      failedBackupsDeleted: failedCount,
      errors: result.errors.length,
    });

    return result;
  } catch (error) {
    logger.error('Backup retention cleanup job failed', {
      error: error instanceof Error ? error.message : String(error),
    });
    throw error;
  }
}
