<?php
namespace Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler;

use Fifa\ConnectServiceBus\Sdk\Api\ApiException;
use Fifa\ConnectServiceBus\Sdk\Exception\UnauthorizedException;

/**
 * Class UnauthorizedRequestHandler
 * @package Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler
 */
class UnauthorizedRequestHandler implements HandlerInterface
{
    /**
     * @var int
     */
    private $errorCode;

    /**
     * Constructor
     *
     * @param int $errorCode
     */
    public function __construct(int $errorCode = 401)
    {
        $this->errorCode = $errorCode;
    }

    /**
     * String representation of the object
     */
    public function __toString()
    {
        return 'ErrorCode: ' . $this->errorCode;
    }

    /**
     * Method handles an UnauthorizedRequestException
     *
     * @param ApiException $e
     * @return UnauthorizedException|null
     */
    public function handle(ApiException $e): ?UnauthorizedException
    {
        if ($e->getCode() == $this->errorCode) {
            return new UnauthorizedException($e);
        }

        return null;
    }
}