import { AutoPostJobLogger } from "@/lib/logging/auto-post-logger";
import { writeSchedulerHeartbeat } from "./scheduler-heartbeat";
import { runScheduledPublish } from "./run-scheduled-publish";

const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
const STARTUP_DELAY_MS = 45_000;

let started = false;
let intervalHandle: ReturnType<typeof setInterval> | null = null;

export function getPollerIntervalMs(): number {
  return Number(process.env.CRON_POLL_INTERVAL_MS) || DEFAULT_INTERVAL_MS;
}

export function isPollerStarted(): boolean {
  return started;
}

/** Idempotent — safe to call from API routes; returns true if poller was just started on this worker. */
export function ensureScheduledPublishPoller(): boolean {
  if (started) return false;
  startScheduledPublishPoller();
  return started;
}

export function startScheduledPublishPoller(): void {
  if (started) return;
  if (process.env.DISABLE_INTERNAL_CRON === "true") return;
  if (!process.env.CRON_SECRET?.trim()) {
    void new AutoPostJobLogger().warn(
      "poller_disabled",
      "CRON_SECRET not set — internal auto-post poller disabled.",
      { status: "misconfigured" },
    );
    return;
  }

  started = true;
  const intervalMs = getPollerIntervalMs();

  const tick = () => {
    void runScheduledPublish("poller").catch((error) => {
      void new AutoPostJobLogger().error("poller_tick_failed", "Poller tick threw an exception.", {
        status: "failed",
        error,
      });
    });
  };

  void writeSchedulerHeartbeat("poller", { pollerStarted: true });
  void new AutoPostJobLogger().info("poller_started", "Internal auto-post poller started.", {
    status: "running",
    details: { intervalMs, startupDelayMs: STARTUP_DELAY_MS, pid: process.pid },
  });

  setTimeout(tick, STARTUP_DELAY_MS);
  intervalHandle = setInterval(tick, intervalMs);
}

export function stopScheduledPublishPoller(): void {
  if (intervalHandle) clearInterval(intervalHandle);
  intervalHandle = null;
  if (started) {
    void new AutoPostJobLogger().info("poller_stopped", "Internal auto-post poller stopped.", {
      status: "stopped",
    });
  }
  started = false;
}
