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

export const runtime = 'nodejs'

// GET /api/agent/pending — reminders edited in-app awaiting push to Apple.
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const pending = await db.reminder.findMany({
    // Existing Apple items are keyed by externalId; app-created reminders
    // (pendingAction=create) have none yet and are keyed by app id.
    // Scoped to the Apple owner: EventKit runs under one iCloud account, so
    // another member's reminders must never be pushed into it. They stay
    // app-only, which is the documented limit of household accounts.
    where: {
      ownerId: await appleOwnerId(),
      syncState: 'PENDING_PUSH',
      OR: [{ externalId: { not: null } }, { pendingAction: 'create' }],
    },
    include: { list: { select: { name: true } } },
  })

  return NextResponse.json({
    reminders: pending.map(r => ({
      id: r.id,
      externalId: r.externalId,
      pendingAction: r.pendingAction,
      title: r.title,
      notes: r.notes ?? undefined,
      dueDate: r.dueDate ? r.dueDate.toISOString() : undefined,
      priority: r.priority ?? undefined,
      list: r.list?.name ?? undefined,
    })),
  })
}
