import { describe, test, expect } from 'vitest'
import { createFlatStore, inMemoryFlatBackend } from '../src/flat-store.js'

describe('T0 flat store (v0.8 MVP)', () => {
  test('provisionFlat stores hashes only — no raw token at rest (INV5)', async () => {
    // Arrange
    const backend = inMemoryFlatBackend()
    const store = createFlatStore(backend)

    // Act
    const { agentToken, clientToken } = await store.provisionFlat('alice')
    const row = await backend.bySubdomain('alice')

    // Assert
    expect(row).not.toBeNull()
    const serialized = JSON.stringify(row)
    expect(serialized).not.toContain(agentToken)
    expect(serialized).not.toContain(clientToken)
    expect(row?.agentTokenHash.startsWith('scrypt$')).toBe(true)
  })

  test('verifyAgentToken true for correct token, false for wrong', async () => {
    const store = createFlatStore()
    const { agentToken } = await store.provisionFlat('bob')
    expect(await store.verifyAgentToken('bob', agentToken)).toBe(true)
    expect(await store.verifyAgentToken('bob', 'wrong-token')).toBe(false)
  })

  test('unknown subdomain resolves to null / false', async () => {
    const store = createFlatStore()
    expect(await store.lookupBySubdomain('nope')).toBeNull()
    expect(await store.verifyAgentToken('nope', 'x')).toBe(false)
  })

  test('two provisions of the same subdomain collide', async () => {
    const store = createFlatStore()
    await store.provisionFlat('carol')
    await expect(store.provisionFlat('carol')).rejects.toThrow(/already provisioned/)
  })
})
