import {
  ChoiceBase,
  DoFetch,
  PlatformError,
  CreatedResource,
} from '../common';
import {
  UsageMetadata,
} from '../usage';
import { EditModel } from '../models';

export enum DataEventObjectType {
  EDIT = 'edit',
}

export interface CreateEditParams {
  model: EditModel;
  input?: string;
  instruction: string;
  n?: number;
  temperature?: number;
  topP?: number;
}

export interface EditChoice extends ChoiceBase {
  text: string;
}

export interface CreateEditDataEvent extends CreatedResource, UsageMetadata {
  object: DataEventObjectType;
  choices: EditChoice[];
}

export function createEdit(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
  params: CreateEditParams,
) {
  doFetch('POST', '/edits', {
    model: params.model ?? EditModel.TEXT_DAVINCI_EDIT_001,
    input: params.input ?? '',
    instruction: params.instruction,
    n: params.n ?? 1,
    temperature: params.temperature ?? 1,
    top_p: params.topP ?? 1,
  } as Record<string, unknown>)
    .then(async (response) => {
      if (!response.ok) {
        this.emit('error', new PlatformError(
          // 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);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}
