import type { PrismaClient } from "@capakraken/db";

const NOTIFICATION_RETENTION_DAYS = 90;

/**
 * Deletes expired invite tokens, expired password-reset tokens, and read
 * notifications older than NOTIFICATION_RETENTION_DAYS.
 *
 * Designed to be called from an admin procedure or a scheduled job.
 * Returns counts of deleted rows for observability.
 */
export async function runPruning(db: PrismaClient): Promise<{
  inviteTokensDeleted: number;
  passwordResetTokensDeleted: number;
  notificationsDeleted: number;
}> {
  const now = new Date();
  const notificationCutoff = new Date(now.getTime() - NOTIFICATION_RETENTION_DAYS * 24 * 60 * 60 * 1000);

  const [inviteResult, resetResult, notificationResult] = await Promise.all([
    db.inviteToken.deleteMany({ where: { expiresAt: { lt: now } } }),
    db.passwordResetToken.deleteMany({ where: { expiresAt: { lt: now } } }),
    db.notification.deleteMany({
      where: {
        readAt: { not: null },
        createdAt: { lt: notificationCutoff },
      },
    }),
  ]);

  return {
    inviteTokensDeleted: inviteResult.count,
    passwordResetTokensDeleted: resetResult.count,
    notificationsDeleted: notificationResult.count,
  };
}
