import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentWrite } from '@/lib/agent-auth'
import { drainQueue } from '@/lib/agent-sessions'

export const runtime = 'nodejs'

const STATUSES = new Set(['RUNNING', 'SUCCEEDED', 'FAILED'])

/** The Mac wrapper reports progress here. Mirrors eorganize's status callback. */
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  const { id } = await params
  if (!/^[0-9a-f-]{36}$/i.test(id)) return new NextResponse('Bad id', { status: 400 })

  let body: {
    status?: string
    errorMessage?: string
    logTail?: string
    completed?: number
    costUsd?: number
  }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }

  const status = body.status?.toUpperCase()
  if (!status || !STATUSES.has(status)) return new NextResponse('Bad status', { status: 400 })

  const now = new Date()
  const data: Record<string, unknown> = { status }
  if (status === 'RUNNING') data.runningAt = now
  if (status === 'SUCCEEDED' || status === 'FAILED') data.finishedAt = now
  if (typeof body.errorMessage === 'string') data.errorMessage = body.errorMessage.slice(0, 1000)
  if (typeof body.logTail === 'string') data.logTail = body.logTail.slice(0, 8000)
  if (typeof body.completed === 'number') data.completed = body.completed
  if (typeof body.costUsd === 'number') data.costUsd = body.costUsd

  try {
    await db.agentSession.update({ where: { id }, data })
  } catch {
    return new NextResponse('Session not found', { status: 404 })
  }

  // The mini just freed up — send whatever Eric queued behind this, now,
  // rather than leaving it for the next hourly tick.
  if (status === 'SUCCEEDED' || status === 'FAILED') {
    try {
      await drainQueue()
    } catch {
      /* the cron will retry */
    }
  }

  return NextResponse.json({ ok: true })
}
