import {describe, expect, test} from 'bun:test'

import {createCoalescer} from '@/lib/coalesce'

describe('createCoalescer', () => {
  test('runs each scheduled effect once on flush', () => {
    const c = createCoalescer()
    const runs: string[] = []
    c.schedule('a', () => runs.push('a'))
    c.schedule('b', () => runs.push('b'))
    c.flush()
    expect(runs.sort()).toEqual(['a', 'b'])
  })

  test('collapses repeated keys to one run (last effect wins)', () => {
    const c = createCoalescer()
    let calls = 0
    let ran = ''
    c.schedule('feed', () => {
      calls++
      ran = 'first'
    })
    c.schedule('feed', () => {
      calls++
      ran = 'second'
    })
    c.flush()
    expect(calls).toBe(1)
    expect(ran).toBe('second')
  })

  test('a second flush with no new schedules runs nothing', () => {
    const c = createCoalescer()
    let calls = 0
    c.schedule('x', () => calls++)
    c.flush()
    c.flush()
    expect(calls).toBe(1)
  })

  test('effects scheduled after a flush run on the next flush', () => {
    const c = createCoalescer()
    const runs: string[] = []
    c.schedule('x', () => runs.push('x1'))
    c.flush()
    c.schedule('x', () => runs.push('x2'))
    c.flush()
    expect(runs).toEqual(['x1', 'x2'])
  })
})
