import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { userFromCaptureToken } from '@/lib/ingest-auth'

export const runtime = 'nodejs'

interface Failure { kind?: string; label?: string; reason?: string }

// GET /api/ingest/capture/:id — what became of a capture, for a client that has
// no session: an iOS Shortcut polling after it posted, a watch, a bot.
//
// Same personal capture token as the POST, and scoped to that account, so one
// household member cannot read another's capture by guessing an id.
//
// `spoken` is the point of this route: one short line fit to be read aloud or
// shown in a notification. It counts what ACTUALLY exists — the records linked
// to this capture right now — rather than echoing the router's own summary,
// which describes what it meant to do.
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await userFromCaptureToken(_req)
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const c = await db.capture.findFirst({
    where: { id, ownerId: user.id },
    select: {
      status: true, error: true, routing: true,
      _count: { select: { reminders: true, events: true, thoughts: true } },
    },
  })
  if (!c) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const routing = (c.routing && typeof c.routing === 'object' ? c.routing : {}) as Record<string, unknown>
  const summary = typeof routing.summary === 'string' ? routing.summary : null
  const failures: Failure[] = Array.isArray(routing.failures) ? (routing.failures as Failure[]) : []

  const parts: string[] = []
  const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
  if (c._count.reminders) parts.push(plural(c._count.reminders, 'reminder'))
  if (c._count.events) parts.push(plural(c._count.events, 'event'))
  if (c._count.thoughts) parts.push(plural(c._count.thoughts, 'note'))

  let spoken: string
  if (c.status === 'FAILED') spoken = `Failed: ${c.error || 'unknown error'}`
  else if (c.status !== 'DONE') spoken = 'Still working on it'
  else if (parts.length) spoken = `${parts.join(', ')}${summary ? ` — ${summary}` : ''}`
  else spoken = summary || 'Nothing created'
  // A dropped integration is the thing most worth hearing about, so it wins the
  // tail of the line rather than being left to the capture detail.
  if (failures.length) {
    spoken += ` (${failures.length} couldn't be done: ${failures.map(f => f.reason).filter(Boolean)[0] || 'see the app'})`
  }

  return NextResponse.json({
    status: c.status,
    done: c.status === 'DONE' || c.status === 'FAILED',
    spoken,
    summary,
    counts: c._count,
    failures,
  })
}
