import { describe, expect, it } from 'vitest'
import { createFlowController } from '../src/transport/flowControl.js'

describe('FlowController (T11)', () => {
  it('pauses at zero credit and resumes on grant', () => {
    const fc = createFlowController()
    fc.initWindow(1, 10)
    expect(fc.consume(1, 8)).toBe(true)
    expect(fc.consume(1, 8)).toBe(false) // only 2 credit left → pause
    fc.grant(1, 16)
    expect(fc.consume(1, 8)).toBe(true)
  })

  it('credit is per-stream: exhausting A does not pause B (starvation guard)', () => {
    const fc = createFlowController()
    fc.initWindow(1, 4)
    fc.initWindow(2, 100)
    expect(fc.consume(1, 4)).toBe(true)
    expect(fc.consume(1, 1)).toBe(false) // A exhausted
    expect(fc.consume(2, 50)).toBe(true) // B unaffected
  })

  it('connection-level (streamId 0) credit caps the whole link', () => {
    const fc = createFlowController()
    fc.initWindow(0, 5) // connection window
    fc.initWindow(1, 1000)
    expect(fc.consume(1, 5)).toBe(true)
    expect(fc.consume(1, 1)).toBe(false) // connection window exhausted despite stream credit
    fc.grant(0, 10)
    expect(fc.consume(1, 1)).toBe(true)
  })

  it('an uninitialized stream has no credit', () => {
    const fc = createFlowController()
    expect(fc.consume(42, 1)).toBe(false)
  })
})
