import { runHeartbeatWorkerOnce } from '../../../../lib/heartbeat-worker.js';
import { requireSession } from '../../../../lib/auth.js';
import { verifyInprocToken } from '../../../../lib/inproc-token.js';

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

// Authorization: in-process daemon ticks present `X-Inproc-Token` (see
// lib/inproc-token.js); operator-driven invocations from a browser tab go
// through the standard session gate. Without one of the two, the route
// returns 401.
export async function POST(req) {
  let body = {};
  try { body = await req.json(); } catch {}
  try {
    if (!verifyInprocToken(req)) {
      await requireSession(req);
    }
    const result = await runHeartbeatWorkerOnce({ workerId: body.worker_id, leaseMs: body.lease_ms });
    return Response.json(result);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
}
