import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'

/**
 * Board API keys (Nash, 2026-10-21). The key itself lives only on the
 * caller's machine (HHA_DEV_TASKS_KEY in that project's env file); the
 * Workspace server keeps only its SHA-256 (DEV_TASKS_API_KEY_HASHES, comma
 * separated), so the server's settings can never leak a usable key. One key
 * per caller (this Mac, another project), each revocable on its own.
 */
export const KEY_PREFIX = 'hhatask_'

export function newBoardKey(): { key: string; sha256: string } {
  const key = `${KEY_PREFIX}${randomBytes(32).toString('base64url')}`
  return { key, sha256: sha256Hex(key) }
}

export function sha256Hex(value: string): string {
  return createHash('sha256').update(value, 'utf8').digest('hex')
}

export function parseKeyHashes(raw: string | undefined): string[] {
  return (raw ?? '').split(',').map((h) => h.trim().toLowerCase()).filter((h) => /^[0-9a-f]{64}$/.test(h))
}

/** True when the bearer key's hash is one of the configured hashes. */
export function verifyBoardKey(authorization: string | null, hashesRaw: string | undefined): boolean {
  const m = /^Bearer\s+(\S{20,200})$/.exec(authorization ?? '')
  if (!m || !m[1].startsWith(KEY_PREFIX)) return false
  const supplied = Buffer.from(sha256Hex(m[1]), 'hex')
  let ok = false
  for (const hash of parseKeyHashes(hashesRaw)) {
    if (timingSafeEqual(supplied, Buffer.from(hash, 'hex'))) ok = true
  }
  return ok
}
