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

use Fifa\ConnectServiceBus\Sdk\Api\ApiException;
use Fifa\ConnectServiceBus\Sdk\Exception\FifaConnectServiceBusSdkException;
use Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler\HandlerInterface;
use Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler\InvalidClientDataHandler;
use Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler\TooManyRequestsHandler;
use Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler\UnauthorizedRequestHandler;

/**
 * Class ApiExceptionHandler
 * @package Fifa\ConnectServiceBus\Sdk\ExceptionHandler
 */
class ApiExceptionHandler
{
    /**
     * Method that wraps ApiException in FifaConnectServiceBusSdkException
     *
     * @param ApiException $exception
     * @param $handlers - objects implementing HandlerInterface
     * @return FifaConnectServiceBusSdkException
     */
    public static function createException(ApiException $exception, ...$handlers) : FifaConnectServiceBusSdkException
    {
        $exceptionHandlers = array_merge(self::getDefaultHandlers(), array_filter(
            $handlers,
            function($arg) {
                return ($arg instanceof HandlerInterface);
            }
        ));

        /** @var HandlerInterface $handler */
        foreach ($exceptionHandlers as $handler) {
            $e = $handler->handle($exception);
            if ($e instanceof FifaConnectServiceBusSdkException) {
                return $e;
            }
        }

        return new FifaConnectServiceBusSdkException($exception);
    }

    /**
     * Returns an array of default exception handlers
     *
     * @return HandlerInterface[]
     */
    private static function getDefaultHandlers(): array
    {
        return array(
            new InvalidClientDataHandler(),
            new UnauthorizedRequestHandler(),
            new TooManyRequestsHandler()
        );
    }
}