/**
 * RFC 7638 / RFC 8037 JWK thumbprint for an Ed25519 (OKP) public key — the `cnf.jkt`
 * proof-of-possession binding (DPoP-style, Finding-4). Members are serialized in the
 * REQUIRED lexicographic order `crv,kty,x` with no whitespace.
 */
import { encodeBase64UrlBytes } from 'relay-contracts'
import { sha256 } from './ed25519.js'

/** JWK `x` value (base64url of the 32-byte raw Ed25519 public key). */
export function ed25519PublicJwkX(rawPublic: Uint8Array): string {
  return encodeBase64UrlBytes(rawPublic)
}

/** Canonical Ed25519 public JWK JSON (RFC 7638 member ordering: crv, kty, x). */
export function ed25519PublicJwkJson(rawPublic: Uint8Array): string {
  return JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: ed25519PublicJwkX(rawPublic) })
}

/** base64url(SHA-256(canonical-JWK)) — the `jkt` thumbprint. */
export async function jwkThumbprint(rawPublic: Uint8Array): Promise<string> {
  const json = ed25519PublicJwkJson(rawPublic)
  const digest = await sha256(new TextEncoder().encode(json))
  return encodeBase64UrlBytes(digest)
}
