import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { visible } from '@/lib/scope'
import { triggerAgent } from '@/lib/agent-trigger'
import { logActivity } from '@/lib/activity'

export const runtime = 'nodejs'

function toDate(v: unknown): Date | null {
  if (typeof v !== 'string' || !v.trim()) return null
  const d = new Date(v)
  return isNaN(d.getTime()) ? null : d
}

// PATCH /api/reminders/:id — edit title/dueDate/priority/listId in-app, then
// queue a push to Apple.
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: Record<string, unknown> = {}
  if (typeof body.title === 'string' && body.title.trim()) data.title = body.title.trim()
  if ('dueDate' in body) data.dueDate = toDate(body.dueDate)
  if ('priority' in body) data.priority = typeof body.priority === 'number' ? body.priority : null
  if ('listId' in body) data.listId = body.listId || null
  if (Object.keys(data).length === 0) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })

  data.syncState = 'PENDING_PUSH'
  data.pendingAction = 'update'
  const target = await db.reminder.findFirst({ where: { id, ...visible.reminder(session.userId) }, select: { id: true } })
  if (!target) return NextResponse.json({ error: 'not found' }, { status: 404 })
  const r = await db.reminder.update({ where: { id }, data })
  logActivity(session.userId, 'reminder.updated', `Edited reminder: ${r.title}`)
  triggerAgent('push').catch(() => {})
  return NextResponse.json({ ok: true })
}

// DELETE /api/reminders/:id — queue deletion (hidden from UI immediately; the
// row is removed once the agent deletes it from Apple).
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
  const target = await db.reminder.findFirst({ where: { id, ...visible.reminder(session.userId) }, select: { id: true } })
  if (!target) return NextResponse.json({ error: 'not found' }, { status: 404 })
  const r = await db.reminder.update({ where: { id }, data: { syncState: 'PENDING_PUSH', pendingAction: 'delete' } })
  logActivity(session.userId, 'reminder.deleted', `Deleted reminder: ${r.title}`)
  triggerAgent('push').catch(() => {})
  return NextResponse.json({ ok: true })
}
