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

export const runtime = 'nodejs'

// POST /api/agent/investigations/:id/result — the mini reporting back.
//
// Two shapes, both through here:
//   { state: "RUNNING" }                       claiming it, before the long call
//   { findings, actions, error }               the answer
//
// Claiming is a separate round trip on purpose. A diagnosis takes minutes, and
// without it the page shows "Queued" for the whole run while something is very
// much happening — which is exactly the kind of silence that makes a person
// press the button again.
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 existing = await db.investigation.findUnique({ where: { id }, select: { id: true } })
  if (!existing) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const body = await req.json().catch(() => ({}))

  if (body.state === 'RUNNING') {
    await db.investigation.update({ where: { id }, data: { state: 'RUNNING', startedAt: new Date() } })
    return NextResponse.json({ ok: true })
  }

  const error = body.error ? String(body.error).slice(0, 500) : null
  const findings = body.findings ? String(body.findings).slice(0, 8000) : null
  // An agent that returns neither a finding nor an error has failed, whatever
  // it thinks. "Done" with nothing to show is the shape of a silent failure,
  // and this dashboard has been bitten by that often enough.
  const useless = !findings && !error

  await db.investigation.update({
    where: { id },
    data: {
      state: error || useless ? 'FAILED' : 'DONE',
      finishedAt: new Date(),
      findings,
      actions: Array.isArray(body.actions) && body.actions.length ? body.actions.slice(0, 20) : undefined,
      error: error || (useless ? 'the agent finished without saying anything' : null),
      // The transcription of what he SAID, written back so the thread shows his
      // words. Without this a spoken note is a question only the agent ever
      // read, and "why did it do that" becomes unanswerable a week later.
      ...(body.note ? { note: String(body.note).slice(0, 2000) } : {}),
    },
  })
  return NextResponse.json({ ok: true })
}
