/**
 * T11 — multi-device key adapters (authenticated channel, NOT a QR).
 *
 * Multi-device does NOT ship a key over a scannable QR. Each device runs its OWN §4.4 handshake
 * gated by an account-derived `deviceAuthProof` (P5) and independently re-derives the recoverable
 * `K_content` (T10). No plaintext key material ever transits a shoulder-surfable/relay-readable
 * channel. `buildClientHandshake` is the frozen §4.4 assembly: it wires the injected
 * AuthorizedDeviceContext into `createClientHandshake` with the default Ed25519 verifier.
 *
 * There is deliberately NO function here (or anywhere in the public surface) that serializes a
 * session/content key to a transferable string or QR blob (guards a plaintext-QR regression).
 */
import type {
  AeadAlg,
  AuthorizedDeviceContext,
  ClientHandshake,
  DevicePinStore,
} from 'relay-contracts'
import { nobleEd25519Verifier } from './ed25519.js'
import { createClientHandshake } from './handshake.js'

/** Frozen §4.4 factory P6 calls: build a client handshake from an authorized device context. */
export function buildClientHandshake(
  ctx: AuthorizedDeviceContext,
  hostId: string,
  aeadOffer: readonly AeadAlg[],
): ClientHandshake {
  return createClientHandshake({
    aeadOffer,
    deviceAuthProofProvider: ctx.deviceAuthProofProvider,
    verifier: nobleEd25519Verifier(),
    pinStore: ctx.pinStore,
    hostId,
  })
}

/**
 * In-memory TOFU pin store (a `DevicePinStore` adapter). P6 injects a persistent implementation
 * (localStorage/IndexedDB); this is the injectable default for Node hosts and tests. `pin` sets a
 * value even if one exists — changing an existing pin is the CALLER's explicit decision (the
 * handshake never auto-repins on a mismatch; see T8).
 */
export class MemoryDevicePinStore implements DevicePinStore {
  #pins = new Map<string, string>()

  async get(hostId: string): Promise<string | null> {
    return this.#pins.get(hostId) ?? null
  }

  async pin(hostId: string, enrollFpr: string): Promise<void> {
    this.#pins.set(hostId, enrollFpr)
  }
}
