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

export const runtime = 'nodejs'

// GET /api/agent/reminders — open reminders for the organize pass (with their
// Apple list, as a hint for theming), bucketed by account. Topics are a
// cross-list grouping lens, and they are drawn per account: "Errands" should
// mean one person's errands.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const reminders = await db.reminder.findMany({
    where: { completed: false, OR: [{ pendingAction: null }, { pendingAction: { not: 'delete' } }] },
    orderBy: { createdAt: 'asc' },
    select: { id: true, title: true, ownerId: true, list: { select: { name: true } } },
    take: 500,
  })
  const flat = reminders.map(r => ({ id: r.id, title: r.title, list: r.list?.name ?? null, ownerId: r.ownerId }))
  return NextResponse.json({
    owners: byOwner(flat).map(g => ({ ownerId: g.ownerId, items: g.rows })),
  })
}

// POST /api/agent/reminders — 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())

  let updated = 0
  for (const it of items) {
    if (!it.id) continue
    const res = await db.reminder.updateMany({ where: { id: it.id, ownerId }, data: { topic: it.topic || null } })
    updated += res.count
  }
  logActivity(ownerId, 'organize.reminders', `Organize pass: ${updated} reminders grouped`)
  return NextResponse.json({ ok: true, updated })
}
