import { ConsumeStream, DoFetch } from '../../../packages/request';
import { PlatformApiError } from '../../../common';

export interface CreateTextToSpeechParams {
  voiceId: string;
  text: string;
  voiceSettings?: {
    stability?: number;
    similarityBoost?: number;
  };
}

export function createTextToSpeech(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
  consumeStream: ConsumeStream,
  params: CreateTextToSpeechParams,
) {
  doFetch('POST', `/text-to-speech/${params.voiceId}/stream`, {
    text: params.text,
    voice_settings: params.voiceSettings,
  } as Record<string, unknown>)
    .then(async (response) => {
      if (!response.ok) {
        this.emit('error', new PlatformApiError(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          `Create chat completion returned with status: ${response.status}`,
          response,
        ));
        this.emit('end');
        return;
      }

      await consumeStream(response);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}
