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

export const runtime = 'nodejs'

// POST — the loop reporting what it did with Eric's instruction.
//
//   { answer }                 the transcript of what he said, written back so
//                              the card shows his words and not just a mic icon
//   { sentSummary }            the reply actually sent; moves it to SENT
//   { error }                  could not act on it — stays ANSWERED, so the
//                              next tick tries again rather than losing it
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const row = await db.quailDecision.findUnique({ where: { id }, select: { id: true, state: true } })
  if (!row) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const b = await req.json().catch(() => ({}))
  const data: Record<string, unknown> = {}
  if (b.answer) data.answer = String(b.answer).slice(0, 2000)

  if (b.sentSummary) {
    // Only ever from ANSWERED. A loop that "sent" a reply to a question Eric
    // has not answered has invented his side of it, and that is worth
    // refusing loudly rather than recording.
    if (row.state !== 'ANSWERED') {
      return NextResponse.json({ error: `cannot send: that decision is ${row.state}, not ANSWERED` }, { status: 409 })
    }
    data.sentSummary = String(b.sentSummary).slice(0, 1500)
    data.sentAt = new Date()
    data.state = 'SENT'
  }

  if (!Object.keys(data).length) return NextResponse.json({ error: 'nothing to record' }, { status: 400 })
  await db.quailDecision.update({ where: { id }, data })
  return NextResponse.json({ ok: true })
}
