import { cronDaemonTick } from '@/lib/runtime.js';
import { verifyInprocToken } from '@/lib/inproc-token.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

// Internal dispatcher hit by the in-process auto-tick in `lib/db.js`. Also
// callable manually for one-shot cron processing. The body is optional; the
// only knob is `interval_ms` which controls the lookback window for "due"
// schedules.
//
// Authorization: the daemon sends `X-Inproc-Token` on every tick (see
// lib/inproc-token.js). Manual callers must hold a valid session. Remote
// attackers without either cannot fire scheduled work.
export async function POST(req) {
  if (!verifyInprocToken(req)) {
    try {
      await requireSession(req);
    } catch (err) {
      if (err && typeof err === 'object' && err.status) {
        return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
      }
      throw err;
    }
  }
  let body = {};
  try {
    body = await req.json();
  } catch {
    body = {};
  }
  const rawInterval = body?.interval_ms != null ? Number(body.interval_ms) : NaN;
  const intervalMs = Number.isFinite(rawInterval) && rawInterval > 0
    ? rawInterval
    : Number(process.env.CRON_DAEMON_INTERVAL_MS || 30000);
  const lastTickAt = typeof body.last_tick_at === 'number' ? body.last_tick_at : null;
  try {
    const result = await cronDaemonTick({ lastTickAt, intervalMs });
    return Response.json({ ok: true, ...result });
  } catch (err) {
    console.warn('[api/cron/tick] error:', err?.message || err);
    return Response.json({ ok: false, error: err?.message || String(err) }, { status: 500 });
  }
}
