import { purgeUnattached } from './bug-files.service';
import { sendLeftovers } from './bug-notify.service';
import { runWeeklySummary } from './bug-insights.service';
import { purgeDeliveries } from './bug-github.service';

/**
 * The bug tracker's background work (docs/bug-tracker-plan.md), hourly:
 *   - remove files uploaded for a report or comment nobody sent (BT2);
 *   - send notification emails a restart left unsent (BT4);
 *   - on Monday morning, the super admin's weekly summary (BT4);
 *   - forget GitHub deliveries older than 30 days (BT6).
 * Each step claims its work in the database, so it is safe on several instances.
 */
let timer: NodeJS.Timeout | null = null;

async function step(what: string, work: () => Promise<number>, said: (n: number) => string) {
  try {
    const n = await work();
    // eslint-disable-next-line no-console
    if (n) console.log(`[bugs] ${said(n)}`);
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[bugs] ${what} failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}

export async function bugTick(now = new Date()) {
  await step('file clean-up', purgeUnattached, (n) => `removed ${n} file(s) that were never attached`);
  await step('notification emails', () => sendLeftovers(now), (n) => `sent ${n} notification email(s) left over`);
  await step('weekly summary', () => runWeeklySummary(now), (n) => `sent the weekly summary to ${n} super admin(s)`);
  await step('GitHub delivery clean-up', () => purgeDeliveries(now), (n) => `forgot ${n} old GitHub deliver${n === 1 ? 'y' : 'ies'}`);
}

export function startBugTrackerScheduler(): void {
  if (timer) return;
  timer = setInterval(() => void bugTick(), 60 * 60 * 1000);
  timer.unref();
}
