import { CustomError } from "ts-custom-error";

export class SignaldError extends CustomError {
  public msg: string;
  constructor(public errorType: string, public message: string) {
    super(`[${errorType}]: ${message}`);
    this.errorType = errorType;
    this.message = `[${errorType}]: ${message}`;
    this.msg = `${message}`;
  }
}

export class CaptchaRequiredException extends SignaldError {
  constructor(errorType: string, message: string) {
    super(errorType, message);
  }
}

const isBoolean = (v) => "boolean" === typeof v;
const isString = (v) => typeof v === "string" || v instanceof String;

export const throwOnError = (response: any) => {
  if (response.type === "profile_not_available")
    throw new SignaldError("profile_not_available", response.data);

  const { data } = response;
  let error;
  if (Array.isArray(data)) {
    error = response.error || false;
  } else if (isString(data)) {
    error = false;
  } else {
    error = response.error || data?.error || false;
  }
  if (error) {
    let type_, msg;
    if (isBoolean(error)) {
      type_ = response.type;
      msg = data.message || "";
      let req = data.request || "";
      msg += req.toString();
    } else {
      type_ = error.type;
      msg = error.message || "";
      msg += (error.validationResults || [""]).join("");
    }
    if (!type_) type_ = response.error_type;
    if (type_ === "CaptchaRequired")
      throw new CaptchaRequiredException(type_, msg);
    throw new SignaldError(type_, msg);
  }
};
