import 'server-only'
import { createHash, timingSafeEqual } from 'crypto'
import { db } from '@/lib/db'

/**
 * Resolve the account behind a personal capture token, or null.
 *
 * Tokens are per DEVICE (CaptureToken), so revoking the watch leaves the
 * phone's Shortcut working. Looked up by SHA-256, so the database holds
 * nothing replayable; the extra compare guards against a lookup matching on
 * anything but equality.
 *
 * `lastUsedAt` is stamped on every accepted call — it is the only way to tell
 * later which of five tokens is still in a device somebody carries.
 */
export async function userFromCaptureToken(req: Request): Promise<{ id: string } | null> {
  const m = (req.headers.get('authorization') || '').match(/^Bearer\s+(.+)$/i)
  if (!m) return null
  const hash = createHash('sha256').update(m[1].trim()).digest('hex')

  const token = await db.captureToken.findUnique({
    where: { tokenHash: hash },
    select: { id: true, ownerId: true, tokenHash: true },
  })
  if (!token) return null
  const a = Buffer.from(token.tokenHash)
  const b = Buffer.from(hash)
  if (a.length !== b.length || !timingSafeEqual(a, b)) return null

  // Never let bookkeeping fail a capture.
  db.captureToken
    .update({ where: { id: token.id }, data: { lastUsedAt: new Date() } })
    .catch(() => {})

  return { id: token.ownerId }
}
