/** * @ai-summary Job for audit log retention cleanup * @ai-context Runs daily at 3 AM to delete logs older than 90 days */ import { Pool } from 'pg'; import { logger } from '../../../core/logging/logger'; import { AuditLogService } from '../domain/audit-log.service'; import { AuditLogRepository } from '../data/audit-log.repository'; let pool: Pool | null = null; /** * Sets the database pool for the job */ export function setAuditLogCleanupJobPool(dbPool: Pool): void { pool = dbPool; } /** * Retention period in days for audit logs */ const AUDIT_LOG_RETENTION_DAYS = 90; /** * Result of cleanup job */ export interface AuditLogCleanupResult { deletedCount: number; retentionDays: number; success: boolean; error?: string; } /** * Processes audit log retention cleanup */ export async function processAuditLogCleanup(): Promise { if (!pool) { throw new Error('Database pool not initialized for audit log cleanup job'); } const repository = new AuditLogRepository(pool); const service = new AuditLogService(repository); try { logger.info('Starting audit log cleanup job', { retentionDays: AUDIT_LOG_RETENTION_DAYS, }); const deletedCount = await service.cleanup(AUDIT_LOG_RETENTION_DAYS); logger.info('Audit log cleanup job completed', { deletedCount, retentionDays: AUDIT_LOG_RETENTION_DAYS, }); return { deletedCount, retentionDays: AUDIT_LOG_RETENTION_DAYS, success: true, }; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); logger.error('Audit log cleanup job failed', { error: errorMessage }); return { deletedCount: 0, retentionDays: AUDIT_LOG_RETENTION_DAYS, success: false, error: errorMessage, }; } }