// The bridge's handle->did map is PERSISTED, so a restart never drops handle resolution — the bug where an
// OFFLINE peer (served only by the blind-relay, e.g. ashatron) became unresolvable (resolveHandle →
// HandleNotFound) after a bridge restart, because the in-memory map was learned only at front-time and the
// offline peer couldn't re-teach its handle. Fix 1 = load/save the map; Fix 2 = learn it on every announce.
import test from 'brittle'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import Hyperswarm from 'hyperswarm'
import createTestnet from '@hyperswarm/testnet'
import { openCorestore } from 'atproto-store/lib/corestore.js'
import { mkDidRouter } from './mk-did-router.js'
test('handle map persists + survives a bridge restart (offline peer stays resolvable)', async (t) => {
const testnet = await createTestnet(3)
const swarm = new Hyperswarm({ bootstrap: testnet.bootstrap })
const store = openCorestore(mkdtempSync(join(tmpdir(), 'hpr-')))
t.teardown(async () => { try { await swarm.destroy() } catch {} try { await store.close() } catch {} await testnet.destroy() })
// Fix 1: constructing with a persisted map restores handle resolution — no live re-front needed.
const r1 = mkDidRouter(swarm, store, { refreshMs: 0, handles: { 'ashatron.7rnx.net': 'did:plc:ash' } })
t.is(r1.resolveHandle('ashatron.7rnx.net'), 'did:plc:ash', 'loads a persisted handle on construct')
// Fix 1+2: learning a new handle persists it via onHandles (this is what _identify→learn does per announce).
let saved = null
const r2 = mkDidRouter(swarm, store, { refreshMs: 0, onHandles: (o) => { saved = o } })
r2._setHandle('p2p.7rnx.net', 'did:plc:wj62')
t.is(r2.resolveHandle('p2p.7rnx.net'), 'did:plc:wj62', 'learns a new handle')
t.ok(saved && saved['p2p.7rnx.net'] === 'did:plc:wj62', 'persists via onHandles when the map grows')
saved = null
r2._setHandle('p2p.7rnx.net', 'did:plc:wj62') // same mapping again
t.is(saved, null, 'idempotent — no re-persist when nothing changed')
// "Restart": a fresh router loaded with the persisted map resolves BOTH — even the offline peer that
// never reconnects. This is the exact scenario that was broken (ashatron after a bridge restart).
const persisted = { 'ashatron.7rnx.net': 'did:plc:ash', 'p2p.7rnx.net': 'did:plc:wj62' }
const r3 = mkDidRouter(swarm, store, { refreshMs: 0, handles: persisted })
t.is(r3.resolveHandle('ashatron.7rnx.net'), 'did:plc:ash', 'after restart, the OFFLINE peer handle STILL resolves')
t.is(r3.resolveHandle('p2p.7rnx.net'), 'did:plc:wj62', 'after restart, the learned handle persists')
})