import type {
  VoiceProvider,
  VoiceProviderConnectInput,
  VoiceProviderKind,
  VoiceProviderSession,
} from "./types.ts";

export class FailoverVoiceProvider implements VoiceProvider {
  readonly kind: VoiceProviderKind;

  constructor(
    private readonly primary: VoiceProvider,
    private readonly fallbacks: VoiceProvider[],
  ) {
    this.kind = primary.kind;
  }

  async connect(input: VoiceProviderConnectInput): Promise<VoiceProviderSession> {
    const errors: string[] = [];
    for (const provider of [this.primary, ...this.fallbacks]) {
      try {
        return await provider.connect(input);
      } catch (err) {
        errors.push(`${provider.kind}: ${err instanceof Error ? err.message : String(err)}`);
      }
    }
    throw new Error(`All voice providers failed to connect: ${errors.join("; ")}`);
  }
}
