<?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\Api\Exception;

use InPost\International\Api\ApiError;
use InPost\International\Api\Point\Exception\PostCodeNotFoundException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

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

class ApiErrorException extends \RuntimeException implements ApiExceptionInterface
{
    private const CLASS_MAP = [
        PostCodeNotFoundException::ERROR_KEY => PostCodeNotFoundException::class,
    ];

    /**
     * @var ApiError
     */
    private $error;

    /**
     * @var RequestInterface
     */
    private $request;

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

    public function __construct(ApiError $error, RequestInterface $request, ResponseInterface $response)
    {
        parent::__construct($error->getError());
        $this->error = $error;
        $this->request = $request;
        $this->response = $response;
    }

    public static function create(ApiError $error, RequestInterface $request, ResponseInterface $response): self
    {
        /** @var class-string<self> $class */
        $class = self::CLASS_MAP[$error->getKey()] ?? self::class;

        return new $class($error, $request, $response);
    }

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

    public function getRequest(): RequestInterface
    {
        return $this->request;
    }

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

    public function getStatusCode(): int
    {
        return $this->error->getStatus();
    }
}
