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

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

// GET /api/agent/investigations/pending — what the mini has been asked to look at.
//
// Claiming is the caller's job, via the result route's RUNNING transition: this
// only reports. Oldest first and capped at one, because a diagnosis is a long
// Claude call and two at once on the same box help nobody.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const pending = await db.investigation.findMany({
    where: { state: 'QUEUED' },
    orderBy: { createdAt: 'asc' },
    take: 1,
    select: {
      id: true, host: true, checkName: true, checkStatus: true, checkDetail: true, createdAt: true,
      note: true, noteAudio: true,
      // What it concluded last time, so a follow-up argues with its own
      // reasoning instead of re-deriving the whole diagnosis from the dot.
      parent: { select: { findings: true, actions: true, createdAt: true } },
    },
  })
  return NextResponse.json({
    pending: pending.map(p => ({ ...p, hasAudio: Boolean(p.noteAudio), noteAudio: undefined })),
  })
}
