// registry test — the name→moshKey read path against a real HandleRegistry.
// Creates a local registry (writer), claims handles, and asserts resolveMoshKey's
// extraction: prefer metadata.moshKey, fall back to devicePubkey. No network.
import Corestore from 'corestore'
import { HandleRegistry } from 'hyper-identity/handle-registry'
import { moshKeyFromEntry } from '../lib/registry.mjs'
import fs from 'fs'
import os from 'os'
import path from 'path'
let failures = 0
const ok = (cond, msg) => { if (cond) console.log(' ✅ ' + msg); else { console.log(' ❌ ' + msg); failures++ } }
console.log('[registry] name -> moshKey extraction (metadata.moshKey, devicePubkey fallback)')
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hm-reg-'))
const store = new Corestore(dir)
const reg = new HandleRegistry(store) // no bootstrap → this node is the writer
await reg.ready()
const ROOT = 'a'.repeat(64)
const DEVICE = 'b'.repeat(64)
const MOSH = 'c'.repeat(64)
// 1. handle WITH metadata.moshKey → moshKey wins
await reg.claim({ name: 'nodeA', identity: { identityRoot: ROOT, devicePubkey: DEVICE }, metadata: { kind: 'shell', moshKey: MOSH } })
const a = await reg.resolve('nodeA')
ok(a && a.metadata && a.metadata.moshKey === MOSH, 'claim stored metadata.moshKey')
ok(moshKeyFromEntry(a) === MOSH, 'resolveMoshKey prefers metadata.moshKey over devicePubkey')
// 2. handle WITHOUT moshKey → fall back to devicePubkey
await reg.claim({ name: 'nodeB', identity: { identityRoot: ROOT, devicePubkey: DEVICE } })
const b = await reg.resolve('nodeB')
ok(moshKeyFromEntry(b) === DEVICE, 'falls back to devicePubkey when no metadata.moshKey')
// 3. unknown name → null
ok(moshKeyFromEntry(await reg.resolve('nope')) === null, 'unknown name resolves to null')
await reg.close()
try { await store.close() } catch {}
try { fs.rmSync(dir, { recursive: true, force: true }) } catch {}
console.log(failures === 0 ? '\n✅ registry test passed' : '\n❌ registry test failed')
process.exit(failures === 0 ? 0 : 1)