import { describe, test, expect } from 'vitest'
import { createMemoryStores } from '../src/store/memory.js'
import { createRoutingTable, RouteAuthError } from '../src/routing/table.js'
import { createNodeCoordinator } from '../src/routing/nodes.js'
import { createInMemoryRevocationBus } from '../src/routing/bus.js'
import { deriveNodeIdentity, NodeAuthError, type NodeIdentity } from '../src/node-auth/identity.js'
import type { KillSignal } from 'relay-contracts'

const nodeA: NodeIdentity = { nodeId: 'spiffe://relay/node-a' }
const nodeB: NodeIdentity = { nodeId: 'spiffe://relay/node-b' }
const HOST = '33333333-3333-4333-8333-333333333333'

describe('T9 node identity (INV3-analog)', () => {
  test('authorized cert with CN → id; unauthenticated → 401; no CN → 401', () => {
    expect(deriveNodeIdentity({ authorized: true, subjectCommonName: 'node-x' }).nodeId).toBe('node-x')
    expect(() => deriveNodeIdentity({ authorized: false, subjectCommonName: 'node-x' })).toThrow(NodeAuthError)
    expect(() => deriveNodeIdentity({ authorized: true, subjectCommonName: null })).toThrow(NodeAuthError)
    expect(() => deriveNodeIdentity(null)).toThrow(NodeAuthError)
  })
})

describe('T9 routing table (INV7)', () => {
  test('upsert then resolve; foreign relayNodeId rejected', async () => {
    const { routes } = createMemoryStores()
    const table = createRoutingTable({ routes })
    await table.upsertRoute(nodeA, HOST, { relayNodeId: nodeA.nodeId, updatedAt: new Date().toISOString() }, 60)
    expect((await table.resolveRoute(HOST))?.relayNodeId).toBe(nodeA.nodeId)
    await expect(
      table.upsertRoute(nodeA, HOST, { relayNodeId: nodeB.nodeId, updatedAt: new Date().toISOString() }, 60),
    ).rejects.toBeInstanceOf(RouteAuthError)
  })

  test('heartbeat-TTL expiry ⇒ resolveRoute null (fails closed)', async () => {
    const { routes } = createMemoryStores()
    const table = createRoutingTable({ routes })
    await table.upsertRoute(nodeA, HOST, { relayNodeId: nodeA.nodeId, updatedAt: new Date().toISOString() }, 0)
    expect(await table.resolveRoute(HOST)).toBeNull()
  })

  test('foreign node cannot heartbeat/hijack; only holder drops', async () => {
    const { routes } = createMemoryStores()
    const table = createRoutingTable({ routes })
    await table.upsertRoute(nodeA, HOST, { relayNodeId: nodeA.nodeId, updatedAt: new Date().toISOString() }, 60)
    await table.heartbeatRoute(nodeB, HOST, 60) // foreign → no-op
    expect((await table.resolveRoute(HOST))?.relayNodeId).toBe(nodeA.nodeId)
    await expect(table.dropRoute(nodeB, HOST)).rejects.toBeInstanceOf(RouteAuthError)
    await table.dropRoute(nodeA, HOST)
    expect(await table.resolveRoute(HOST)).toBeNull()
  })
})

describe('T10 node registry + graceful drain (INV7)', () => {
  test('beginDrain flips status, returns routed host_ids, publishes per-host KillSignal', async () => {
    const stores = createMemoryStores()
    const bus = createInMemoryRevocationBus()
    const table = createRoutingTable({
      routes: stores.routes,
      nodeStatus: async (id) => (await stores.nodes.get(id))?.status ?? null,
    })
    const coord = createNodeCoordinator({ nodes: stores.nodes, routes: stores.routes, bus })
    const received: KillSignal[] = []
    bus.subscribe((s) => received.push(s))

    await coord.registerNode(nodeA, '10.0.0.1:9000')
    await table.upsertRoute(nodeA, HOST, { relayNodeId: nodeA.nodeId, updatedAt: new Date().toISOString() }, 60)

    const { hostIds } = await coord.beginDrain(nodeA)
    expect(hostIds).toEqual([HOST])
    expect((await stores.nodes.get(nodeA.nodeId))?.status).toBe('draining')
    expect(received.map((s) => s.scope)).toEqual([{ kind: 'host', hostId: HOST }])

    // a draining node stops receiving new upserts
    await expect(
      table.upsertRoute(nodeA, '44444444-4444-4444-8444-444444444444', { relayNodeId: nodeA.nodeId, updatedAt: new Date().toISOString() }, 60),
    ).rejects.toBeInstanceOf(RouteAuthError)

    await coord.completeDrain(nodeA)
    expect(await stores.nodes.get(nodeA.nodeId)).toBeNull()
  })

  test('PTY-survival: draining touches no host/session row', async () => {
    const stores = createMemoryStores()
    const bus = createInMemoryRevocationBus()
    const coord = createNodeCoordinator({ nodes: stores.nodes, routes: stores.routes, bus })
    await coord.registerNode(nodeA, 'addr')
    await coord.beginDrain(nodeA)
    // no host rows were ever created by drain
    expect(await stores.hosts.get(HOST)).toBeNull()
  })
})
