import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentAuth, checkCallbackSecret } from '@/lib/agent-auth'
import { logActivity } from '@/lib/activity'
import { visibleChecklistItemsWhere } from '@/lib/checklist'
import { byOwner, foundingOwnerId } from '@/lib/owner'

export const runtime = 'nodejs'

// GET /api/agent/checklists — active lists + items for the organize pass,
// bucketed by the list's owner.
//
// Categories are per-list already, so bucketing changes nothing about the
// result — it keeps one account's private lists out of the prompt that
// categorizes another's. A HOUSEHOLD list sits in its owner's bucket, which is
// right: everyone looking at it sees the one set of categories.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const lists = await db.checklist.findMany({
    where: { dismissed: false },
    select: {
      id: true,
      name: true,
      ownerId: true,
      items: { where: visibleChecklistItemsWhere(), select: { id: true, title: true, done: true }, orderBy: { createdAt: 'asc' } },
    },
  })
  return NextResponse.json({
    owners: byOwner(lists).map(g => ({ ownerId: g.ownerId, lists: g.rows })),
  })
}

// POST /api/agent/checklists — apply organize results for ONE account.
// Body: { ownerId, items: [{ id, topic }] }
export async function POST(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  if (!checkCallbackSecret(req)) return NextResponse.json({ error: 'bad callback secret' }, { status: 403 })

  const body = await req.json().catch(() => null)
  const items: { id?: string; topic?: string }[] = Array.isArray(body?.items) ? body.items : []

  const requested = typeof body?.ownerId === 'string' ? body.ownerId.trim() : ''
  if (requested && !(await db.user.findUnique({ where: { id: requested }, select: { id: true } }))) {
    return NextResponse.json({ error: 'unknown ownerId' }, { status: 400 })
  }
  const ownerId = requested || (await foundingOwnerId())

  // Items inherit ownership through their list, so that is where the write is
  // pinned.
  let updated = 0
  for (const it of items) {
    if (!it.id) continue
    const res = await db.checklistItem.updateMany({
      where: { id: it.id, list: { ownerId } },
      data: { topic: it.topic || null },
    })
    updated += res.count
  }
  logActivity(ownerId, 'organize.lists', `Organize pass: ${updated} checklist items categorized`)
  return NextResponse.json({ ok: true, updated })
}
