import { describe, test, expect } from 'vitest'
import { createMemoryStores } from '../src/store/memory.js'
import { createAccountRegistry } from '../src/registry/accounts.js'
import { createHostRegistry } from '../src/registry/hosts.js'
import { createSessionRegistry } from '../src/registry/sessions.js'
import {
  createSubdomainAssigner,
  isValidSubdomain,
  normalizeSubdomain,
  assembleFqdn,
} from '../src/subdomain/assign.js'
import { fingerprint } from '../src/ca/fingerprint.js'
import { generateEd25519 } from '../src/util/crypto.js'

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/

function bindInput(accountId: string, subdomain: string) {
  const { publicKeyRaw } = generateEd25519()
  return { accountId, subdomain, agentPubkey: publicKeyRaw, enrollFpr: fingerprint(publicKeyRaw) }
}

describe('T3 account registry (INV8)', () => {
  test('createAccount returns unguessable uuid + active status + seed version', async () => {
    const { accounts } = createMemoryStores()
    const reg = createAccountRegistry({ accounts })
    const a = await reg.createAccount('pro')
    expect(a.accountId).toMatch(UUID_RE)
    expect(a.status).toBe('active')
    expect((await accounts.versions(a.accountId)).length).toBe(1)
  })

  test('setAccountStatus swaps snapshot; prior version stays readable from versions table', async () => {
    const { accounts } = createMemoryStores()
    const reg = createAccountRegistry({ accounts })
    const a = await reg.createAccount('free')
    const next = await reg.setAccountStatus(a.accountId, 'suspended')
    expect(next.status).toBe('suspended')
    const versions = await accounts.versions(a.accountId)
    expect(versions.map((v) => v.status)).toEqual(['active', 'suspended'])
    expect(versions.map((v) => v.version)).toEqual([1, 2]) // strictly monotonic
  })

  test('concurrent setAccountStatus → monotonic versions, no torn read (INV8)', async () => {
    const { accounts } = createMemoryStores()
    const reg = createAccountRegistry({ accounts })
    const a = await reg.createAccount('team')
    await Promise.all([
      reg.setAccountStatus(a.accountId, 'suspended'),
      reg.setAccountStatus(a.accountId, 'active'),
    ])
    const versions = await accounts.versions(a.accountId)
    expect(versions.map((v) => v.version)).toEqual([1, 2, 3])
  })
})

describe('T4 host registry (INV1/INV4/INV8)', () => {
  test('bindHost stores only the public key; enrollFpr is its fingerprint (INV4)', async () => {
    const { hosts } = createMemoryStores()
    const reg = createHostRegistry({ hosts })
    const inp = bindInput('11111111-1111-4111-8111-111111111111', 'alice')
    const host = await reg.bindHost(inp)
    expect(host.enrollFpr).toBe(fingerprint(inp.agentPubkey))
    const dump = JSON.stringify(await hosts.get(host.hostId))
    expect(dump).not.toContain('PRIVATE')
  })

  test('ownsHost(A, hostOwnedByB) → false (INV1 tripwire fact)', async () => {
    const { hosts } = createMemoryStores()
    const reg = createHostRegistry({ hosts })
    const a = '11111111-1111-4111-8111-111111111111'
    const b = '22222222-2222-4222-8222-222222222222'
    const host = await reg.bindHost(bindInput(a, 'alice'))
    expect(await reg.ownsHost(a, host.hostId)).toBe(true)
    expect(await reg.ownsHost(b, host.hostId)).toBe(false)
    expect(await reg.ownsHost(a, 'unknown-host')).toBe(false) // deny-by-default
  })

  test('getHostBySubdomain resolves the stable name; setHostStatus versions', async () => {
    const { hosts } = createMemoryStores()
    const reg = createHostRegistry({ hosts })
    const host = await reg.bindHost(bindInput('11111111-1111-4111-8111-111111111111', 'alice'))
    expect((await reg.getHostBySubdomain('alice'))?.hostId).toBe(host.hostId)
    const revoked = await reg.setHostStatus(host.hostId, 'revoked')
    expect(revoked.status).toBe('revoked')
    expect(revoked.revokedAt).not.toBeNull()
    const versions = await hosts.versions(host.hostId)
    expect(versions.map((v) => v.status)).toEqual(['offline', 'revoked'])
  })

  test('touchLastSeen does NOT create a version row (advisory cache, INV7)', async () => {
    const { hosts } = createMemoryStores()
    const reg = createHostRegistry({ hosts })
    const host = await reg.bindHost(bindInput('11111111-1111-4111-8111-111111111111', 'alice'))
    await reg.touchLastSeen(host.hostId)
    await reg.touchLastSeen(host.hostId)
    expect((await hosts.versions(host.hostId)).length).toBe(1)
  })

  test('bindHost rejects a mismatched enrollFpr', async () => {
    const { hosts } = createMemoryStores()
    const reg = createHostRegistry({ hosts })
    const inp = { ...bindInput('11111111-1111-4111-8111-111111111111', 'alice'), enrollFpr: 'deadbeef' }
    await expect(reg.bindHost(inp)).rejects.toThrow(/enrollFpr/)
  })
})

describe('T5 session registry (INV3/INV6)', () => {
  test('recordSession derives account_id from the host, ignoring any caller value', async () => {
    const stores = createMemoryStores()
    const hostReg = createHostRegistry({ hosts: stores.hosts })
    const sessReg = createSessionRegistry({ sessions: stores.sessions, hosts: stores.hosts })
    const owner = '11111111-1111-4111-8111-111111111111'
    const host = await hostReg.bindHost(bindInput(owner, 'alice'))
    const s = await sessReg.recordSession({ sessionId: 'sess-1', hostId: host.hostId })
    expect(s.accountId).toBe(owner)
    expect(await sessReg.sessionAccount('sess-1')).toBe(owner)
  })

  test('unknown session → null', async () => {
    const stores = createMemoryStores()
    const sessReg = createSessionRegistry({ sessions: stores.sessions, hosts: stores.hosts })
    expect(await sessReg.sessionAccount('nope')).toBeNull()
  })
})

describe('T6 subdomain assignment (INV1)', () => {
  test('reserved words rejected; host-confusion inputs rejected', () => {
    for (const bad of ['www', 'api', 'admin', '_']) expect(isValidSubdomain(bad)).toBe(false)
    expect(isValidSubdomain('a.b')).toBe(false)
    expect(isValidSubdomain('A LICE')).toBe(false)
    expect(isValidSubdomain('-alice')).toBe(false)
    expect(isValidSubdomain('alice')).toBe(true)
    expect(normalizeSubdomain('A LICE!!')).toBe('alice')
    expect(assembleFqdn('alice', 'term.example.com')).toBe('alice.term.example.com')
  })

  test('UNIQUE collision under concurrency → exactly one winner for the exact name', async () => {
    const { subdomains } = createMemoryStores()
    let n = 0
    const assigner = createSubdomainAssigner({ subdomains, suffix: () => String(n++).padStart(4, '0') })
    const [a, b] = await Promise.all([
      assigner.assignSubdomain('acct-a', 'shared'),
      assigner.assignSubdomain('acct-b', 'shared'),
    ])
    expect(new Set([a, b]).size).toBe(2) // never collapses two tenants onto one label
    expect([a, b].filter((x) => x === 'shared').length).toBe(1) // exactly one got the exact name
  })
})
