import { NextResponse } from 'next/server'
import { checkAgentAuth } from '@/lib/agent-auth'
import { tick } from '@/lib/cadence'

export const runtime = 'nodejs'

/**
 * The scheduler. Called hourly by cron on the VPS:
 *
 *   0 * * * * curl -fsS -H "Authorization: Bearer $AGENT_TOKEN" \
 *               https://learn.etpics.com/api/cron/tick
 *
 * Hourly rather than every three weeks on the nose: each tick does at most one
 * thing (only one agent session may be in flight), so frequent cheap ticks are
 * what let a backlog drain and a busy mini get retried without any queue.
 */
export async function POST(req: Request) {
  if (!checkAgentAuth(req)) return new NextResponse('Unauthorized', { status: 401 })
  return NextResponse.json(await tick())
}

// Same thing on GET, so the cron line can be a plain curl.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return new NextResponse('Unauthorized', { status: 401 })
  return NextResponse.json(await tick())
}
