import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'

export const runtime = 'nodejs'

// POST /api/push/subscribe — register this device for Web Push.
// DELETE — unregister it.
//
// Keyed on the endpoint, which is the browser's own identifier for this
// device+install. Re-subscribing from the same device updates the row rather
// than piling up duplicates that would each ring separately.
export async function POST(req: Request) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const body = await req.json().catch(() => null)
  const endpoint: string | undefined = body?.endpoint
  const p256dh: string | undefined = body?.keys?.p256dh
  const auth: string | undefined = body?.keys?.auth
  if (!endpoint || !p256dh || !auth) {
    return NextResponse.json({ error: 'endpoint and keys required' }, { status: 400 })
  }

  await db.pushSubscription.upsert({
    where: { endpoint },
    update: { ownerId: session.userId, p256dh, auth, userAgent: req.headers.get('user-agent') || null },
    create: { ownerId: session.userId, endpoint, p256dh, auth, userAgent: req.headers.get('user-agent') || null },
  })
  return NextResponse.json({ ok: true })
}

export async function DELETE(req: Request) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const body = await req.json().catch(() => null)
  const endpoint: string | undefined = body?.endpoint
  if (!endpoint) return NextResponse.json({ error: 'endpoint required' }, { status: 400 })
  // Scoped to the caller: an endpoint is not a secret, so deleting by endpoint
  // alone would let one account unsubscribe another's device.
  await db.pushSubscription.deleteMany({ where: { endpoint, ownerId: session.userId } })
  return NextResponse.json({ ok: true })
}
