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/digest/pending — what the mini still owes an answer to.
//
// The digest body comes with each one so the agent has the context without a
// second call: the whole point of a reply is that it is ABOUT that text.
//
// Oldest first, capped: a backlog should drain in order, and a burst of
// questions should not become one enormous Claude call.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const pending = await db.digestReply.findMany({
    where: { status: 'PENDING' },
    orderBy: { createdAt: 'asc' },
    take: 5,
    select: {
      id: true, prompt: true, createdAt: true, audioPath: true,
      digest: { select: { id: true, title: true, summary: true, body: true, createdAt: true } },
    },
  })

  return NextResponse.json({
    pending: pending.map(p => ({
      id: p.id,
      prompt: p.prompt,
      // The worker transcribes when this is set and prompt is empty; whisper
      // lives on the mini, so the question is not readable until it gets there.
      hasAudio: Boolean(p.audioPath),
      askedAt: p.createdAt.toISOString(),
      digest: {
        title: p.digest.title,
        summary: p.digest.summary,
        body: p.digest.body,
        at: p.digest.createdAt.toISOString(),
      },
    })),
  })
}
