import cron from 'node-cron';
import { db } from '../config/database.js';
import { auditLogs } from '../db/schema.js';
import { lt } from 'drizzle-orm';
import { logger } from '../utils/logger.js';

const RETENTION_DAYS = 7;

/**
 * Delete audit logs older than RETENTION_DAYS
 */
export const cleanupOldAuditLogs = async () => {
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS);

  try {
    const result = await db
      .delete(auditLogs)
      .where(lt(auditLogs.createdAt, cutoffDate))
      .returning({ id: auditLogs.id });

    const deletedCount = result.length;

    if (deletedCount > 0) {
      logger.info(`Audit cleanup: deleted ${deletedCount} old logs`);
    }

    return deletedCount;
  } catch (error) {
    logger.error('Audit cleanup failed', error);
    throw error;
  }
};

/**
 * Start the audit logs cleanup cron job
 * Runs every day at midnight (00:00)
 * @returns {{ name: string, schedule: string }}
 */
export const startAuditCleanupCron = () => {
  cron.schedule('0 0 * * *', () => {
    cleanupOldAuditLogs().catch(() => {});
  });

  return { name: 'Audit cleanup (00:00)', schedule: '00:00' };
};
