import { prisma } from "../db";
import { logger } from "../logger";

/**
 * Cleanup old audit logs
 *
 * Removes audit logs older than the specified retention period, except for critical events.
 * Critical events (SECURITY_BREACH, ADMIN_ACCESS, DATA_EXPORT) are kept forever.
 *
 * @param retentionDays - Number of days to retain logs (default: 90)
 * @returns Number of deleted logs
 */
export async function cleanupOldAuditLogs(retentionDays = 90): Promise<number> {
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - retentionDays);

  try {
    const deleted = await prisma.audit_logs.deleteMany({
      where: {
        createdAt: { lt: cutoffDate },
        // Keep critical events forever
        action: {
          notIn: ["SECURITY_BREACH", "ADMIN_ACCESS", "DATA_EXPORT"],
        },
      },
    });

    logger.info("Audit log cleanup completed", {
      deleted: deleted.count,
      retentionDays,
      cutoffDate: cutoffDate.toISOString(),
    });

    return deleted.count;
  } catch (error) {
    logger.error("Audit log cleanup failed", {
      error: error instanceof Error ? error.message : "Unknown error",
      stack: error instanceof Error ? error.stack : undefined,
    });
    throw error;
  }
}

// If run directly (via tsx)
if (require.main === module) {
  cleanupOldAuditLogs()
    .then((count) => {
      console.log(`✅ Deleted ${count} old audit log entries`);
      process.exit(0);
    })
    .catch((error) => {
      console.error("❌ Audit log cleanup failed:", error);
      process.exit(1);
    });
}
