/**
 * A4 — device registry (mirrors registry/hosts.ts). Proves: create/get; versioned status swap
 * (INV8 append-only companion rows + atomic pointer swap); per-account device CAP enforcement;
 * per-account enroll RATE-LIMIT; ownership deny-by-default.
 */
import { describe, test, expect } from 'vitest'
import {
  createDeviceRegistry,
  createMemoryDeviceStore,
  DeviceLimitError,
  type RegisterDeviceInput,
} from '../../src/registry/devices.js'

const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'
const ACCOUNT_B = '22222222-2222-4222-8222-222222222222'

function input(overrides: Partial<RegisterDeviceInput> = {}): RegisterDeviceInput {
  return {
    accountId: ACCOUNT_A,
    subdomainScope: 'alice',
    ecPubkeySpki: new Uint8Array([1, 2, 3, 4]),
    attestationLevel: 'none',
    ...overrides,
  }
}

describe('A4 device registry', () => {
  test('registerDevice → getDevice returns the persisted record with a serial + notAfter', async () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
    const rec = await devices.registerDevice(input())
    expect(rec.deviceId.length).toBeGreaterThan(0)
    expect(rec.accountId).toBe(ACCOUNT_A)
    expect(rec.subdomainScope).toBe('alice')
    expect(rec.status).toBe('active')
    expect(rec.serial.length).toBeGreaterThan(0)
    expect(Date.parse(rec.notAfter)).toBeGreaterThan(Date.now())
    expect(await devices.getDevice(rec.deviceId)).toEqual(rec)
  })

  test('ecPubkeySpki is defensively copied (public key only, immutable)', async () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
    const src = new Uint8Array([9, 9, 9])
    const rec = await devices.registerDevice(input({ ecPubkeySpki: src }))
    src[0] = 0 // mutate the caller's buffer
    expect(Array.from(rec.ecPubkeySpki)).toEqual([9, 9, 9])
  })

  test('setDeviceStatus revokes with a versioned snapshot (INV8)', async () => {
    const store = createMemoryDeviceStore()
    const devices = createDeviceRegistry({ devices: store })
    const rec = await devices.registerDevice(input())
    const revoked = await devices.setDeviceStatus(rec.deviceId, 'revoked')
    expect(revoked.status).toBe('revoked')
    expect(revoked.revokedAt).not.toBeNull()
    const versions = await store.versions(rec.deviceId)
    expect(versions.length).toBe(2) // insert + revoke
    expect(versions[1]?.status).toBe('revoked')
  })

  test('ownsDevice is deny-by-default (unknown device / foreign account ⇒ false)', async () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
    const rec = await devices.registerDevice(input())
    expect(await devices.ownsDevice(ACCOUNT_A, rec.deviceId)).toBe(true)
    expect(await devices.ownsDevice(ACCOUNT_B, rec.deviceId)).toBe(false)
    expect(await devices.ownsDevice(ACCOUNT_A, 'nope')).toBe(false)
  })

  test('per-account device CAP is enforced (active count only)', async () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), deviceCap: 2 })
    await devices.assertUnderCap(ACCOUNT_A) // 0 < 2
    const r1 = await devices.registerDevice(input())
    await devices.registerDevice(input())
    await expect(devices.assertUnderCap(ACCOUNT_A)).rejects.toBeInstanceOf(DeviceLimitError)
    // a different account is unaffected
    await devices.assertUnderCap(ACCOUNT_B)
    // revoking one frees a slot
    await devices.setDeviceStatus(r1.deviceId, 'revoked')
    await devices.assertUnderCap(ACCOUNT_A)
  })

  test('per-account enroll RATE-LIMIT throws after the window budget', () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), rateMax: 2 })
    devices.checkRateLimit(ACCOUNT_A)
    devices.checkRateLimit(ACCOUNT_A)
    expect(() => devices.checkRateLimit(ACCOUNT_A)).toThrow(DeviceLimitError)
    // a different account has its own budget
    expect(() => devices.checkRateLimit(ACCOUNT_B)).not.toThrow()
  })

  test('DeviceLimitError carries a machine code (cap vs rate) but a uniform message', async () => {
    const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), deviceCap: 0 })
    await devices.registerDevice(input()).catch(() => undefined)
    await expect(devices.assertUnderCap(ACCOUNT_A)).rejects.toMatchObject({ code: 'cap_exceeded' })
  })
})
