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

export const runtime = 'nodejs'

// POST /api/agent/checks/acknowledge — quiet a dot Eric has decided about.
//
// Deliberately NOT a way to make something green. The check keeps reporting
// what is true, with its real status and detail; acknowledging only stops it
// colouring the card and counting as a problem. Faking health is the one thing
// this dashboard must never do — it exists because silence used to read as
// health, and a green dot that means "someone waved it away" is that bug with
// better manners.
//
// The acknowledgement is pinned to the DETAIL text as a signature. If the check
// starts saying something different, /api/monitor/ingest drops the ack on the
// next report: he acknowledged a sentence he read, not the row forever.
export async function POST(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const body = await req.json().catch(() => ({}))
  const host = String(body.host || '')
  const name = String(body.name || '')
  const note = String(body.note || '').slice(0, 300)
  if (!host || !name) return NextResponse.json({ error: 'host and name are required' }, { status: 400 })
  if (!note) return NextResponse.json({ error: 'note is required — an acknowledgement with no reason is unreadable later' }, { status: 400 })

  const check = await db.hostCheck.findUnique({ where: { host_name: { host, name } }, select: { detail: true, status: true } })
  if (!check) return NextResponse.json({ error: `no check ${name} on ${host}` }, { status: 404 })
  if (check.status === 'OK') return NextResponse.json({ error: 'that check is already green — nothing to acknowledge' }, { status: 400 })

  await db.hostCheck.update({
    where: { host_name: { host, name } },
    data: { ackedAt: new Date(), ackNote: note, ackSignature: check.detail },
  })
  return NextResponse.json({ ok: true, acknowledged: { host, name, whileItSays: check.detail } })
}

// DELETE — un-acknowledge, so it speaks up again.
export async function DELETE(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const body = await req.json().catch(() => ({}))
  const host = String(body.host || '')
  const name = String(body.name || '')
  if (!host || !name) return NextResponse.json({ error: 'host and name are required' }, { status: 400 })
  await db.hostCheck.updateMany({ where: { host, name }, data: { ackedAt: null, ackNote: null, ackSignature: null } })
  return NextResponse.json({ ok: true })
}
