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

export const runtime = 'nodejs'

// POST /api/agent/pushed — the agent reports an in-app edit was applied to Apple.
// Body: { externalId, action, ok } — or { id, action: "create", externalId, ok }
// for app-created reminders. We clear the pending state either way (mirror
// reconciles any true failures); delete actions remove the row.
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)

  if (body?.action === 'create') {
    if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 400 })
    // On failure leave the row PENDING_PUSH so the next push retries it.
    if (body.ok && body.externalId) {
      try {
        await db.reminder.update({
          where: { id: body.id },
          data: { externalId: body.externalId, syncState: 'SYNCED', pendingAction: null, lastSyncedAt: new Date() },
        })
      } catch {
        // externalId already taken — the mirror raced us and inserted its own
        // row for the new Apple item; drop our still-unsynced copy.
        await db.reminder.deleteMany({ where: { id: body.id, externalId: null } })
      }
    }
    return NextResponse.json({ ok: true })
  }

  if (!body?.externalId || !body?.action) {
    return NextResponse.json({ error: 'externalId and action required' }, { status: 400 })
  }

  if (body.action === 'delete') {
    await db.reminder.deleteMany({ where: { externalId: body.externalId } })
  } else {
    await db.reminder.updateMany({
      where: { externalId: body.externalId },
      data: { syncState: 'SYNCED', pendingAction: null, lastSyncedAt: new Date() },
    })
  }
  return NextResponse.json({ ok: true })
}
