/* eslint-disable @typescript-eslint/promise-function-async */
import delay from "delay";
import * as pollDelay from "../../internal/pollDelay";
import { secToHuman } from "../../internal/secToHuman";
import * as wrapSigInt from "../../internal/wrapSigInt";

/**
 * When running e.g. move() in a unit test, we must not intercept a SIGINT,
 * since it wouldn't allow the test to be aborted with ^C. But also, we want to
 * artificially interrupt the move if the test takes too long.
 */
export function mockTestWrapSigInt(forceAbortInSec = 60): void {
  const timeStart = Date.now();
  jest.spyOn(wrapSigInt, "wrapSigInt").mockImplementation(async (body) =>
    body(() => {
      if (Date.now() - timeStart > forceAbortInSec * 1000) {
        throw `Aborted due to the test taking more than ${secToHuman(forceAbortInSec)}`;
      }
    }),
  );
  // Shorter poll delay in tests to make them faster.
  jest.spyOn(pollDelay, "pollDelay").mockImplementation(() => delay(100));
}
