import { env } from "../../config/env";
import { expireDueDynamicQrTransactions } from "./dynamicQrExpiry";

type SchedulerRunResult = Awaited<ReturnType<typeof expireDueDynamicQrTransactions>>;

type SchedulerStatus = {
  enabled: boolean;
  running: boolean;
  interval_ms: number;
  limit: number;
  last_started_at: string | null;
  last_finished_at: string | null;
  last_result: SchedulerRunResult | null;
  last_error: string | null;
};

const enabled = String(env.DYNAMIC_QR_EXPIRY_SCHEDULER_ENABLED).toLowerCase() !== "false";
const intervalMs = Math.max(env.DYNAMIC_QR_EXPIRY_SWEEP_INTERVAL_MS || 60000, 5000);
const limit = Math.min(Math.max(env.DYNAMIC_QR_EXPIRY_SWEEP_LIMIT || 100, 1), 500);

let timer: NodeJS.Timeout | null = null;
let running = false;
let lastStartedAt: string | null = null;
let lastFinishedAt: string | null = null;
let lastResult: SchedulerRunResult | null = null;
let lastError: string | null = null;

async function runSweep() {
  if (running) {
    return;
  }

  running = true;
  lastStartedAt = new Date().toISOString();
  lastError = null;

  try {
    lastResult = await expireDueDynamicQrTransactions({
      limit,
      source: "system",
      request_id: `dynamic_qr_expiry_scheduler_${lastStartedAt}`
    });
  } catch (error) {
    lastError = error instanceof Error ? error.message : "UNKNOWN_ERROR";
  } finally {
    running = false;
    lastFinishedAt = new Date().toISOString();
  }
}

export function startDynamicQrExpiryScheduler() {
  if (!enabled || timer) {
    return;
  }

  timer = setInterval(() => {
    void runSweep();
  }, intervalMs);
  timer.unref?.();
}

export function getDynamicQrExpirySchedulerStatus(): SchedulerStatus {
  return {
    enabled,
    running,
    interval_ms: intervalMs,
    limit,
    last_started_at: lastStartedAt,
    last_finished_at: lastFinishedAt,
    last_result: lastResult,
    last_error: lastError
  };
}
