/**
 * The API answered with an error. `code` is the machine-readable error ("invalid_amount", "transaction_not_found", …),
 * `status` the HTTP status (undefined for connection errors), `message` the readable text some errors carry.
 */
export class HBankError extends Error {
  readonly code: string;
  readonly status: number | undefined;
  readonly body: unknown;

  constructor(code: string, status: number | undefined, message?: string, body?: unknown) {
    super(message ? `${code}: ${message}` : code);
    this.name = "HBankError";
    this.code = code;
    this.status = status;
    this.body = body;
  }

  /** The readable message the API sent with the error, if any. */
  get detail(): string | undefined {
    const b = this.body as { message?: unknown } | undefined;
    return typeof b?.message === "string" ? b.message : undefined;
  }
}

/** 401 `missing_api_key` or 403 `invalid_api_key`: the key is missing, wrong or revoked, or the business is inactive. */
export class AuthenticationError extends HBankError {
  constructor(code: string, status: number, message?: string) {
    super(code, status, message, message);
    this.name = "AuthenticationError";
  }
}

/**
 * HBank couldn't be reached, or the request timed out (`code` is "connection_failed" or "timeout").
 * The request may or may not have reached HBank: before retrying a refund, check `refunded` with `getPayment`.
 */
export class HBankConnectionError extends HBankError {
  constructor(code: "connection_failed" | "timeout", message: string, cause?: unknown) {
    super(code, undefined, message);
    this.name = "HBankConnectionError";
    if (cause !== undefined) (this as { cause?: unknown }).cause = cause;
  }
}
