import { purgeBin } from './crm-contacts.service';
import { purgeDealBin } from './crm-deals.service';
import { tick } from './crm-automation';
import { env } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';

/**
 * The CRM's background work. For now: empty the bin of contacts deleted more
 * than 30 days ago, hourly. Idempotent, so several instances are harmless.
 */
let timer: NodeJS.Timeout | null = null;

async function binTick() {
  try {
    const purged = (await purgeBin()) + (await purgeDealBin());
    // Reminder claims only matter for a few days (nothing older is chased).
    await prismaUnscoped.crmReminderClaim.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 30 * 86_400_000) } } });
    // eslint-disable-next-line no-console
    if (purged) console.log(`[crm] removed ${purged} record(s) from the bin for good`);
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[crm] bin purge failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}

let mailTimer: NodeJS.Timeout | null = null;
let running = false;

/** Alerts, reminders and summaries: every five minutes, one run at a time. */
async function mailTick() {
  if (running) return;
  running = true;
  try {
    await tick(new Date());
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[crm] scheduled email run failed: ${err instanceof Error ? err.message : String(err)}`);
  } finally {
    running = false;
  }
}

export function startCrmScheduler(): void {
  if (timer) return;
  timer = setInterval(() => void binTick(), 60 * 60 * 1000);
  timer.unref();
  setTimeout(() => void binTick(), 30_000).unref();
  // Under the test clock the suites drive the clock themselves.
  if (env.CRM_TEST_CLOCK) return;
  mailTimer = setInterval(() => void mailTick(), 5 * 60 * 1000);
  mailTimer.unref();
  setTimeout(() => void mailTick(), 45_000).unref();
}
