type TeardownStep = () => unknown;

export const teardownWorkspace = async (steps: {
  stopHeartbeat: TeardownStep;
  removeActive: TeardownStep;
  appendEvent?: TeardownStep;
  abortAgent?: TeardownStep;
  removeMaterializedEnv?: TeardownStep;
  markStopped?: TeardownStep;
  closeAgent?: TeardownStep;
  stopContainer?: TeardownStep;
  release: TeardownStep;
}) => {
  const errors: unknown[] = [];
  const call = (step: TeardownStep | undefined) => {
    if (!step) return Promise.resolve();
    try {
      return Promise.resolve(step()).catch((error: unknown) => {
        errors.push(error);
      });
    } catch (error) {
      errors.push(error);
      return Promise.resolve();
    }
  };

  const immediate = [call(steps.stopHeartbeat), call(steps.removeActive)];
  await Promise.all(immediate);
  await call(steps.appendEvent);
  await call(steps.abortAgent);
  await call(steps.removeMaterializedEnv);
  await call(steps.markStopped);
  await call(steps.closeAgent);
  await call(steps.stopContainer);
  await call(steps.release);
  return { errors };
};
