<?php

namespace Fifa\ConnectId\Sdk\MessageHandlers;

use Exception;
use Fifa\ConnectId\Sdk\Exception\RegistrationFacadeException;
use Fifa\ConnectServiceBus\Sdk\Message\Message;

class GenericMessageHandler implements MessageHandlerInterface
{
    /**
     * @var callable
     */
    private $handler;

    public function __construct(callable $messageHandler)
    {
        $this->handler = $messageHandler;
    }

    public function canHandle(?string $messageType): bool
    {
        return true;
    }

    /**
     * @throws RegistrationFacadeException
     */
    public function handle(?string $messageType, Message $message)
    {
        try {
            call_user_func_array($this->handler, [$message]);
        } catch (Exception $e) {
            $exceptionMessage = 'Generic message was not properly handled by the client.';
            throw new RegistrationFacadeException($exceptionMessage, 0, $e);
        }
    }

    /**
     * String representation of the object
     */
    public function __toString()
    {
        return MessageHandlersUtil::FullName($this);
    }
}