import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { createAddonManager, createSignedAddonPackage, type AddonManifest } from '../src/facade/addonGovernance'

const manifest = (version: string, permissions: AddonManifest['permissions'] = ['geometry.read']): AddonManifest => ({ id: 'measure-addon', version, name: 'Measure', entrypoint: 'facade.measure', permissions, dependencies: [] })
describe('addon governance', () => {
  it('verifies, installs, updates and rolls back signed Facade-only packages', () => {
    const manager = createAddonManager({ trustedKeys: { release: 'test-secret' } }); const first = createSignedAddonPackage(manifest('1.0.0'), 'commands:v1', 'release', 'test-secret'); const second = createSignedAddonPackage(manifest('1.1.0'), 'commands:v2', 'release', 'test-secret')
    assert.equal(manager.verify(first).valid, true); assert.equal(manager.install(first).revision, 1); assert.equal(manager.update(second).revision, 2); assert.equal(manager.rollback('measure-addon').manifest.version, '1.0.0'); assert.equal(manager.snapshot().catalog[0].manifest.version, '1.0.0'); manager.remove('measure-addon'); assert.equal(manager.snapshot().catalog.length, 0)
  })
  it('rejects forged signatures, disallowed permissions and tampered payloads', () => {
    const manager = createAddonManager({ trustedKeys: { release: 'test-secret' } }); const unsafe = createSignedAddonPackage(manifest('1.0.0', ['network']), 'commands', 'release', 'test-secret'); assert.throws(() => manager.install(unsafe), /permission exceeds policy/)
    const forged = { ...createSignedAddonPackage(manifest('1.0.0'), 'commands', 'release', 'wrong'), payload: 'tampered' }; assert.throws(() => manager.install(forged), /digest mismatch/)
    const unknown = createSignedAddonPackage(manifest('1.0.0'), 'commands', 'unknown', 'test-secret'); assert.throws(() => manager.install(unknown), /untrusted or invalid signature/)
  })
})
