<?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\ApiProblem;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

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

class ApiProblemException extends \RuntimeException implements ApiExceptionInterface
{
    private const CLASS_MAP = [
        ValidationException::PROBLEM_TYPE => ValidationException::class,
        ValidationFailedException::PROBLEM_TYPE => ValidationFailedException::class,
        PayerNotFoundException::PROBLEM_TYPE => PayerNotFoundException::class,
    ];

    /**
     * @var ApiProblem
     */
    private $problem;

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

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

    public function __construct(ApiProblem $problem, RequestInterface $request, ResponseInterface $response)
    {
        parent::__construct($problem->getTitle());
        $this->problem = $problem;
        $this->request = $request;
        $this->response = $response;
    }

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

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

    public function getProblem(): ApiProblem
    {
        return $this->problem;
    }

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

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

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