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

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

// POST /api/digest/ingest — a timer files a digest for /health to show.
// Auth: agent bearer token, same as /api/monitor/ingest.
//
// Arriving unread is the whole point: readAt stays null until Eric opens it.
//
// Retention is handled here rather than by a sweeper, because the only process
// that knows a new one exists is the one delivering it. Thirty of them is a
// month of mornings — enough to look back, small enough that nobody has to
// think about the table.
const KEEP = 30

const BodySchema = z.object({
  kind: z.string().min(1).max(32).default('inbox'),
  title: z.string().min(1).max(200),
  summary: z.string().min(1).max(400),
  body: z.string().min(1).max(20000),
  // Defaults true: a digest that forgot to say should be seen, not silently
  // swallowed. An extra badge costs a glance; a missing one costs the point.
  notable: z.boolean().default(true),
})

export async function POST(req: Request) {
  if (!checkAgentAuth(req)) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  }

  let raw: unknown
  try {
    raw = await req.json()
  } catch {
    return NextResponse.json({ error: 'bad json' }, { status: 400 })
  }

  const parsed = BodySchema.safeParse(raw)
  if (!parsed.success) {
    return NextResponse.json({ error: 'bad payload', issues: parsed.error.issues.slice(0, 5) }, { status: 400 })
  }
  const { kind, title, summary, body, notable } = parsed.data

  const digest = await db.digest.create({ data: { kind, title, summary, body, notable } })

  // Trim the tail of this kind only, so a future digest type cannot evict this one.
  const stale = await db.digest.findMany({
    where: { kind },
    orderBy: { createdAt: 'desc' },
    skip: KEEP,
    select: { id: true },
  })
  if (stale.length) {
    await db.digest.deleteMany({ where: { id: { in: stale.map(s => s.id) } } })
  }

  return NextResponse.json({ ok: true, id: digest.id, pruned: stale.length })
}
