import { createAgent, upsertSchedule } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(req) {
  try {
    await requireSession(req);
    const body = await req.json();
    const result = createAgent(body);
    if (result.agent.schedule && result.agent.schedule !== 'on demand')
      upsertSchedule({ agent_id: result.agent.id, schedule: result.agent.schedule, action_kind: body.action_kind || 'agent-tick' });
    return Response.json(result);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ error: err.message }, { status: 400 });
  }
}
