import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { visible } from '@/lib/scope'

export const runtime = 'nodejs'

// PATCH /api/checklist-items/:id — toggle ({done}) and/or rename ({title}).
export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const body = await req.json().catch(() => ({}))
  const data: { done?: boolean; title?: string; optional?: boolean; completedAt?: Date | null } = {}
  if (typeof body.done === 'boolean') {
    data.done = body.done
    // Stamp/clear the completion time so the 24h auto-hide can age it out.
    data.completedAt = body.done ? new Date() : null
  }
  if (typeof body.optional === 'boolean') data.optional = body.optional
  if (typeof body.title === 'string' && body.title.trim()) data.title = body.title.trim()
  if (Object.keys(data).length === 0) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })

  const { count } = await db.checklistItem.updateMany({ where: { id, ...visible.checklistItem(session.userId) }, data })
  if (count === 0) return NextResponse.json({ error: 'not found' }, { status: 404 })
  return NextResponse.json({ ok: true })
}

// DELETE /api/checklist-items/:id
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  await db.checklistItem.deleteMany({ where: { id, ...visible.checklistItem(session.userId) } })
  return NextResponse.json({ ok: true })
}
