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

export enum DataEventObjectType {
  MODEL = 'model',
}

export type ModelId = string;

export interface ModelData {
  id: ModelId;
  object: DataEventObjectType,
  owned_by: string;
  permission: string[];
}

export interface ListModelsResponse {
  object: ResponseObjectType;
  data: ModelData[];
}

export function listModels(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
) {
  doFetch('GET', '/models')
    .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 ListModelsResponse;
      this.emit('data', responseData);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}

export function retrieveModel(
  this: NodeJS.EventEmitter,
  doFetch: DoFetch,
  modelId: ModelId,
) {
  doFetch('GET', `/models/${modelId}`)
    .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 ModelData;
      this.emit('data', responseData);
      this.emit('end');
    })
    .catch((err) => {
      this.emit('error', err as Error);
      this.emit('end');
    });

  return this;
}
