export type CommandResult = { exitCode: 0 } | { exitCode: number; message: string };

export function success(): CommandResult {
  return { exitCode: 0 };
}

export function failure(message: string, exitCode = 1): CommandResult {
  return { exitCode, message };
}

export function silentFailure(exitCode = 1): CommandResult {
  return { exitCode, message: "" };
}

export async function runCommand(
  fn: () => CommandResult | Promise<CommandResult>,
): Promise<CommandResult> {
  const result = await fn();
  if (result.exitCode !== 0 && "message" in result && result.message) {
    console.error(result.message);
  }
  return result;
}

export async function executeCommand(
  fn: () => CommandResult | Promise<CommandResult>,
): Promise<never> {
  const result = await runCommand(fn);
  process.exit(result.exitCode);
}
