import { Batch } from "./models/types";
import { pullAt } from "lodash";

export enum ERROR_MESSAGE_TIP {
  QUERY_TIMEOUT = "error/message/query/runtime/timeout",
  ACCESS_DENIED = "error/message/security/access-denied",
  NOT_FOUND = "error/message/eno/not-found",
  INTERNAL = "error/message/server/internal",
}

// Throws an error if an error (not in the skipErrors) is found in the batch, if skipErrors is provided, errors defined will be skipped,
// so the enos returned will not have the the same length of the batch.
export function checkBatchForError(
  batch: Batch,
  skipErrors: ERROR_MESSAGE_TIP[] = []
) {
  const indexToRemove: number[] = [];

  batch.forEach((eno, index) => {
    if (eno.getType() === "error") {
      if (
        (skipErrors as string[]).indexOf(
          eno.getFieldStringValue("error/message/tip")
        ) !== -1
      ) {
        indexToRemove.push(index);
      } else {
        throw new Error(JSON.stringify(eno));
      }
    }
  });

  pullAt(batch, indexToRemove);

  return batch;
}
