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

// https://docs.elevenlabs.io/api-reference/voices

export interface Voice {
  voice_id: string;
  name: string;
  category: string;
}

export function getVoices(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
) {
  doFetch('GET', '/voices')
    .then(async (response) => {
      if (!response.ok) {
        this.emit('error', new PlatformApiError(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          `Request from platform returned with status: ${response.status}`,
          response,
        ));
        this.emit('end');
        return;
      }

      const responseData = await response.json() as Record<string, unknown>;
      this.emit('data', responseData.voices as Voice[]);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}
