/**
 * P5 verifying-key registry. `verifyCapabilityToken` / `verifyDeviceProof` are frozen §4.3/§4.4
 * signatures with NO key parameter, so the P5 public verifying key is configured at startup and
 * read here. Signing keys are passed explicitly to issue/sign functions (never held globally).
 *
 * INV9: the key is loaded from the secret manager / env, validated at startup, and NEVER logged.
 */
import { importEd25519PublicRaw } from '../crypto/ed25519.js'
import { decodeBase64UrlBytes } from 'relay-contracts'

let verifyKey: CryptoKey | null = null

export class KeyConfigError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'KeyConfigError'
  }
}

/** Configure the P5 Ed25519 public verifying key (called once at startup / in test setup). */
export function configureVerifyKey(key: CryptoKey): void {
  verifyKey = key
}

/** Load the verifying key from `RELAY_AUTH_VERIFY_PUBKEY` (base64url raw Ed25519). INV9. */
export async function loadVerifyKeyFromEnv(env: NodeJS.ProcessEnv = process.env): Promise<void> {
  const raw = env.RELAY_AUTH_VERIFY_PUBKEY
  if (raw === undefined || raw.length === 0) {
    throw new KeyConfigError('RELAY_AUTH_VERIFY_PUBKEY is not configured')
  }
  verifyKey = await importEd25519PublicRaw(decodeBase64UrlBytes(raw))
}

export function getVerifyKey(): CryptoKey {
  if (verifyKey === null) {
    throw new KeyConfigError('P5 verifying key not configured (call configureVerifyKey/loadVerifyKeyFromEnv)')
  }
  return verifyKey
}

/** TEST-ONLY reset so suites do not leak key state into each other. */
export function resetVerifyKeyForTest(): void {
  verifyKey = null
}
