import { env } from '../../config/env';
import { pollBuilds } from './blog-builds.service';
import { releaseScheduled } from './blog-posts.service';

/**
 * The blog's background work, every minute (docs/blog-cms-plan.md, B2):
 * scheduled posts whose time has come go live, sent builds are followed to
 * live or failed, and a waiting build is sent. pm2 runs the API as a single
 * process (ecosystem.config.js), and a run never overlaps the one before.
 * Off with DISABLE_BLOG_PUBLISH_JOB=true.
 */
let timer: NodeJS.Timeout | null = null;
let running = false;

export async function blogTick(now = new Date()) {
  if (running) return;
  running = true;
  try {
    const released = await releaseScheduled(now);
    // eslint-disable-next-line no-console
    if (released) console.log(`[blog] ${released} scheduled post(s) went live`);
    await pollBuilds();
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[blog] publish job failed: ${err instanceof Error ? err.message : String(err)}`);
  } finally {
    running = false;
  }
}

export function startBlogScheduler(): void {
  if (env.DISABLE_BLOG_PUBLISH_JOB || timer) return;
  setTimeout(() => void blogTick(), 30_000).unref();
  timer = setInterval(() => void blogTick(), 60_000);
  timer.unref();
}
