/**
 * Snapshot Collector
 *
 * Periodische Metrik-Erfassung, laeuft im Queue-Worker PM2-Prozess.
 * Sammelt alle 60s (konfigurierbar) System-Metriken und speichert
 * sie in MonitoringSnapshots. Evaluiert dabei Alert-Regeln.
 */

import { collectMetrics } from "./monitoring-service";
import { AlertEvaluator } from "./alert-evaluator";

let interval: ReturnType<typeof setInterval> | null = null;
const alertEvaluator = new AlertEvaluator();

/** Cached Payload instance — resolved once, reused on every tick. */
let cachedPayload: any = null;

async function getPayloadInstance(): Promise<any> {
  if (cachedPayload) return cachedPayload;
  const { getPayload } = await import("payload");
  const config = (await import(/* @vite-ignore */ "@payload-config")).default;
  cachedPayload = await getPayload({ config });
  return cachedPayload;
}

export async function startSnapshotCollector(): Promise<void> {
  const INTERVAL = parseInt(process.env.MONITORING_SNAPSHOT_INTERVAL || "60000", 10);
  console.log(`[SnapshotCollector] Starting (interval: ${INTERVAL}ms)`);

  // Run immediately once, then on interval
  await collectAndSave();

  interval = setInterval(async () => {
    await collectAndSave();
  }, INTERVAL);
}

async function collectAndSave(): Promise<void> {
  try {
    const payload = await getPayloadInstance();

    const metrics = await collectMetrics();

    await (payload as any).create({
      collection: "monitoring-snapshots",
      data: {
        timestamp: new Date().toISOString(),
        ...metrics,
      },
    });

    // Evaluate alert rules against collected metrics
    await alertEvaluator.evaluateRules(payload as any, metrics);
  } catch (error) {
    console.error("[SnapshotCollector] Error:", error);
    // Reset cache on error so next tick re-resolves
    cachedPayload = null;
  }
}

export async function stopSnapshotCollector(): Promise<void> {
  if (interval) {
    clearInterval(interval);
    interval = null;
  }
  console.log("[SnapshotCollector] Stopped");
}
