// Persistence (issue #35): a daemon restarts. Orgs created/joined in a
// prior run must be re-opened from the local index on ready(), not lost.
import test from 'brittle'
import Corestore from 'corestore'
import { mkdtempSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
import { HyperOrgs } from '../index.js'
test('orgs survive a restart (re-opened from local index)', async (t) => {
const dir = mkdtempSync(join(tmpdir(), 'hyper-orgs-persist-'))
// ── first run: create two orgs ──
let store = new Corestore(dir)
let orgs = new HyperOrgs(store, { namespace: 'persist' })
await orgs.ready()
await orgs.create('alpha', 'group', { displayName: 'Alpha' })
await orgs.create('beta', 'group')
await orgs.addResource('alpha', 'repo-1')
await orgs.close()
await store.close()
// ── restart: fresh instances on the SAME storage dir ──
store = new Corestore(dir)
orgs = new HyperOrgs(store, { namespace: 'persist' })
await orgs.ready()
const names = (await orgs.list()).map(o => o.name).sort()
t.alike(names, ['alpha', 'beta'], 'both orgs re-opened after restart')
const alpha = await orgs.get('alpha')
t.ok(alpha, 'alpha readable after restart')
t.alike(alpha.resources, ['repo-1'], 'alpha state intact')
// re-opened created org is still writable (same namespace → same writer)
t.ok(orgs.getOrgRoom('alpha').writable, 'creator still writable after restart')
await orgs.addResource('beta', 'repo-2')
t.alike((await orgs.get('beta')).resources, ['repo-2'], 'can still write after restart')
t.teardown(async () => {
try { await orgs.close() } catch {}
try { await store.close() } catch {}
})
})