<?php

namespace Fifa\ConnectId\Sdk\Exception;

use Exception;
use Fifa\ConnectId\Sdk\Api\ApiException;

/**
 * Class FifaConnectIdException
 * @package Fifa\ConnectId\Sdk\Exception
 */
class FifaConnectIdException extends Exception
{
    /**
     * @var ApiException
     */
    private $apiException;

    /**
     * @var string
     */
    protected $message;

    /**
     * @var int
     */
    protected $code;

    /**
     * Constructor
     *
     * @param ApiException $apiException
     * @param null|string $message
     * @param null|int $code
     */
    public function __construct(ApiException $apiException, $message = null, $code = null)
    {
        $this->message = is_string($message) ? $message : $apiException->getMessage();
        $this->code = is_int($code) ? $code : $apiException->getCode();

        parent::__construct($this->message, $this->code, $apiException);
        $this->apiException = $apiException;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return sprintf('%s (%s): %s', get_class($this), $this->code, $this->message);
    }

    /**
     * @return ApiException
     */
    protected function getApiException(): ApiException
    {
        return $this->apiException;
    }

    /**
     * Gets the HTTP response header
     *
     * @return string HTTP response header
     */
    public function getResponseHeaders(): string
    {
        return $this->getApiException()->getResponseHeaders();
    }

    /**
     * Gets the HTTP body of the server response either as Json or string
     *
     * @return mixed HTTP body of the server response either as Json or string
     */
    public function getResponseBody()
    {
        return $this->getApiException()->getResponseBody();
    }

    /**
     * Gets the deserialized response object (during deserialization)
     *
     * @return mixed the deserialized response object
     */
    public function getResponseObject()
    {
        return $this->getApiException()->getResponseObject();
    }
}