import { NextResponse } from 'next/server'
import { z } from 'zod'
import { db } from '@/lib/db'
import { getSession } from '@/lib/auth'

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

// POST /api/digest/read — mark one digest read, clearing its "New" badge.
//
// Session auth, not agent auth: this is the reader saying they have read it,
// and it is the one piece of state on /health that a person owns rather than a
// timer. Idempotent — opening an already-read digest must not move the
// timestamp, or "read 3 days ago" would reset every time it is glanced at.
export async function POST(req: Request) {
  const session = await getSession()
  if (!session) 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 = z.object({ id: z.string().min(1).max(64) }).safeParse(raw)
  if (!parsed.success) return NextResponse.json({ error: 'id required' }, { status: 400 })

  const { count } = await db.digest.updateMany({
    where: { id: parsed.data.id, readAt: null },
    data: { readAt: new Date() },
  })

  return NextResponse.json({ ok: true, changed: count })
}
