import { ErrorCode } from './error-code';

export function throwOnInvliadResponse(
  status: number,
  responseBody?: any,
  ignore404: boolean = false
) {
  if (status >= 200 && status < 300) {
    return;
  }

  if (status === 404 && ignore404) {
    return;
  }

  let code: ErrorCode;
  let errorMessage: string;

  if (status === 400) {
    code = ErrorCode.API_ERROR_BAD_REQUEST;
    errorMessage = responseBody ?? 'Invalid arguments';
  } else if (status === 401 || status === 403) {
    code = ErrorCode.API_ERROR_UNAUTHORIZED;
    errorMessage =
      responseBody ?? 'User is not authorized. Check validity of access token';
  } else if (status === 500) {
    code = ErrorCode.API_ERROR_INTERNAL_SERVER_ERROR;
    errorMessage =
      responseBody ??
      'abl server sent internal server error. Please try again later.';
  } else {
    code = ErrorCode.API_ERROR;
    errorMessage = responseBody ?? 'Request failed with unknown error';
  }

  throw {
    code: code,
    message: `Received HTTP status code ${status} from abl API.`,
    apiError: errorMessage,
  };
}
