import { RoomEvent, type Room } from 'livekit-client'

/** A scoped microphone opens only after the actual voice worker confirms its selection. */
export function waitForVoicePermit(room: Room, permitId: string, stateCode: string | null): Promise<void> {
  return new Promise((resolve, reject) => {
    const matches = () => Array.from(room.remoteParticipants.values()).some(participant =>
      participant.attributes['workspace.permit_id'] === permitId && participant.attributes['workspace.state_code'] === stateCode)
    const cleanup = () => {
      clearTimeout(timer)
      room.off(RoomEvent.ParticipantAttributesChanged, check)
      room.off(RoomEvent.ParticipantConnected, check)
      room.off(RoomEvent.Disconnected, disconnected)
    }
    const check = () => { if (matches()) { cleanup(); resolve() } }
    const disconnected = () => { cleanup(); reject(new Error('Voice disconnected before the selected permit was confirmed.')) }
    const timer = setTimeout(() => {
      cleanup()
      reject(new Error('Voice has not confirmed the selected permit. The voice service needs to be updated and reconnected.'))
    }, 20_000)
    room.on(RoomEvent.ParticipantAttributesChanged, check)
    room.on(RoomEvent.ParticipantConnected, check)
    room.on(RoomEvent.Disconnected, disconnected)
    check()
  })
}
