import { DoFetch } from '../../../packages/request';
import { EmbeddingModel } from '../models';
import { PlatformApiError } from '../../../common';
import { ResponseObjectType } from '../common';
import { PromptUsage, UsageMetadata } from '../usage';

export enum DataEventObjectType {
  EMBEDDING = 'embedding',
}

export interface CreateEmbeddingParams {
  model: EmbeddingModel;
  input: string | number[] | string[] | number[][];
  user?: string;
}

export interface Embedding {
  object: DataEventObjectType;
  embedding: number[];
  index: number;
}

export interface CreateEmbeddingResponse extends UsageMetadata<PromptUsage> {
  object: ResponseObjectType;
  data: Embedding[];
  model: EmbeddingModel;
}

export function createEmbedding(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
  params: CreateEmbeddingParams,
) {
  doFetch('POST', '/embeddings', {
    model: params.model,
    input: params.input,
    user: params.user,
  })
    .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;
      }

      const responseData = await response.json() as CreateEmbeddingResponse;
      this.emit('data', responseData);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}
