<?php

declare(strict_types=1);

namespace HBank;

/**
 * The API answered with an error, or couldn't be reached.
 *
 * - `$errorCode`: machine-readable ("invalid_amount", "transaction_not_found", "invalid_api_key", "missing_api_key",
 *   "connection_failed", "timeout", ...). Exception::getCode() is the HTTP status.
 * - `$status`: the HTTP status, 0 when HBank couldn't be reached. After a connection error the request may or may not
 *   have reached HBank: before retrying a refund, check `refunded` with getPayment().
 * - `$detail`: the readable message some errors carry.
 */
final class HBankException extends \RuntimeException
{
    public function __construct(
        public readonly string $errorCode,
        public readonly int $status,
        public readonly ?string $detail = null,
        public readonly ?array $body = null,
    ) {
        parent::__construct($detail === null ? $errorCode : "{$errorCode}: {$detail}", $status);
    }

    public function errorCode(): string
    {
        return $this->errorCode;
    }

    public function isAuthentication(): bool
    {
        return $this->status === 401 || $this->status === 403;
    }

    public function isConnection(): bool
    {
        return $this->status === 0;
    }
}
