import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Room } from 'livekit-client'
import { RoomEvent } from 'livekit-client'
import { waitForVoicePermit } from '@/lib/voice/permit-confirmation'
afterEach(() => vi.useRealTimers())
function fixture(permit: string, state: string) {
  const handlers = new Map<string, () => void>()
  const attributes = { 'workspace.permit_id': permit, 'workspace.state_code': state }
  const room = { remoteParticipants: new Map([['agent', { attributes }]]),
    on: (event: string, callback: () => void) => handlers.set(event, callback),
    off: (event: string) => handlers.delete(event),
  } as unknown as Room
  return { room, handlers, attributes }
}
describe('voice worker selection acknowledgement', () => {
  it('accepts only the exact permit and state loaded by the voice worker', async () => {
    const { room, handlers, attributes } = fixture('other-permit', 'LA')
    let confirmed = false
    const ready = waitForVoicePermit(room, 'selected-permit', 'LA').then(() => { confirmed = true })
    await Promise.resolve()
    expect(confirmed).toBe(false)
    attributes['workspace.permit_id'] = 'selected-permit'
    handlers.get(RoomEvent.ParticipantAttributesChanged)!()
    await ready
    expect(confirmed).toBe(true)
    expect(handlers.size).toBe(0)
  })
  it('rejects a worker that never confirms the selected permit', async () => {
    vi.useFakeTimers()
    const { room } = fixture('other-permit', 'AL')
    const failure = expect(waitForVoicePermit(room, 'selected-permit', 'LA')).rejects.toThrow('selected permit')
    await vi.advanceTimersByTimeAsync(20_000)
    await failure
  })
  it('accepts a worker that joins with its selection already set', async () => {
    const { room, handlers } = fixture('other-permit', 'LA')
    room.remoteParticipants.clear()
    const ready = waitForVoicePermit(room, 'selected-permit', 'LA')
    room.remoteParticipants.set('agent', { attributes: { 'workspace.permit_id': 'selected-permit', 'workspace.state_code': 'LA' } } as never)
    handlers.get(RoomEvent.ParticipantConnected)!()
    await ready
    expect(handlers.size).toBe(0)
  })
})
