// workers/purge-worker.ts
//
// Standalone background worker. Run this as its own long-lived Node process
// (e.g. `node -r ts-node/register workers/purge-worker.ts`, or compiled and
// run via PM2/Docker/systemd) alongside your Next.js server when self-hosting.
//
// It hard-deletes every TempEmail whose expiresAt has passed. Because
// InboundMessage.tempEmail has `onDelete: Cascade` in the Prisma schema,
// deleting the TempEmail row automatically cascades to delete every
// associated InboundMessage in the same transaction — no orphaned rows.

import cron from "node-cron";
import { prisma } from "../lib/prisma";

export interface PurgeResult {
  expiredEmailsDeleted: number;
  ranAt: string;
}

/**
 * Deletes all TempEmail rows (and cascaded InboundMessage rows) where
 * expiresAt <= now. Safe to call repeatedly / idempotent.
 */
export async function purgeExpiredTempEmails(): Promise<PurgeResult> {
  const now = new Date();

  try {
    const result = await prisma.tempEmail.deleteMany({
      where: {
        expiresAt: { lte: now },
      },
    });

    if (result.count > 0) {
      console.info(
        `[purge-worker] Deleted ${result.count} expired temp email(s) and their messages at ${now.toISOString()}`
      );
    }

    return { expiredEmailsDeleted: result.count, ranAt: now.toISOString() };
  } catch (err) {
    console.error("[purge-worker] Purge run failed:", err);
    throw err;
  }
}

/**
 * Starts the recurring cron schedule. Runs every 15 minutes by default —
 * frequent enough that expired inboxes disappear promptly without hammering
 * the database. Adjust the cron expression as needed.
 */
export function startPurgeWorker(cronExpression = "*/15 * * * *") {
  console.info(`[purge-worker] Scheduling purge job with cron: "${cronExpression}"`);

  const task = cron.schedule(cronExpression, async () => {
    try {
      await purgeExpiredTempEmails();
    } catch (err) {
      // Swallow here so a single failed run doesn't kill the scheduler;
      // the error is already logged inside purgeExpiredTempEmails.
    }
  });

  return task;
}

// Allow running this file directly: `ts-node workers/purge-worker.ts`
if (require.main === module) {
  startPurgeWorker();
  console.info("[purge-worker] Worker started. Press Ctrl+C to stop.");

  // Run once immediately on boot so we don't wait 15 minutes for the first pass.
  purgeExpiredTempEmails().catch(() => {
    /* already logged */
  });

  process.on("SIGINT", async () => {
    console.info("[purge-worker] Shutting down...");
    await prisma.$disconnect();
    process.exit(0);
  });
}
