<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\OAuth2\Exception;

use Psr\Http\Message\ResponseInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class AccessTokenRequestException extends RuntimeException
{
    /**
     * @var string
     */
    private $error;

    /**
     * @var ResponseInterface
     */
    private $response;

    /**
     * @var string|null
     */
    private $description;

    public function __construct(string $error, ResponseInterface $response, string $description = null, string $message = '', int $code = 0)
    {
        parent::__construct($message, $code);

        $this->error = $error;
        $this->response = $response;
        $this->description = $description;
    }

    public static function create(array $data, ResponseInterface $response): self
    {
        $error = $data['error'];
        $description = $data['error_description'] ?? null;

        $message = sprintf('Access token response error: "%s".', $error);
        if (null !== $description) {
            $message = sprintf('%s Error description: "%s".', $message, $description);
        }

        return new self($error, $response, $description, $message);
    }

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

    public function getResponse(): ResponseInterface
    {
        return $this->response;
    }

    public function getErrorDescription(): ?string
    {
        return $this->description;
    }
}
