import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentWrite } from '@/lib/agent-auth'
import { buildStateSnapshot, persistGeneratedSet } from '@/lib/generator'

export const runtime = 'nodejs'

/**
 * POST /api/agent/items — a generated set.
 *
 * Lands as PENDING_REVIEW. Every item is re-validated here (see
 * persistGeneratedSet): this is JSON off a pipe, and an item naming a construct
 * the boy isn't measured on, or missing its scoring criteria, would poison the
 * measurement rather than merely look wrong.
 */
export async function POST(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  let body: { sessionId?: string; payload?: unknown; modelId?: string; costUsd?: number }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }

  if (!body.sessionId || !body.payload || !body.modelId) {
    return NextResponse.json(
      { error: 'sessionId, payload and modelId are required' },
      { status: 400 },
    )
  }

  const session = await db.agentSession.findUnique({ where: { id: body.sessionId } })
  if (!session || session.kind !== 'GENERATE' || !session.studentId) {
    return NextResponse.json({ error: 'not a generation session' }, { status: 400 })
  }

  try {
    const snapshot = await buildStateSnapshot(session.studentId, session.track)
    const result = await persistGeneratedSet({
      studentId: session.studentId,
      payload: body.payload as Record<string, unknown>,
      modelId: body.modelId,
      stateSnapshot: snapshot,
      track: session.track,
      costUsd: body.costUsd ?? null,
    })
    return NextResponse.json({ ok: true, ...result })
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'failed to persist' },
      { status: 400 },
    )
  }
}
