<?php

namespace Fifa\ConnectId\Sdk\MessageHandlers;

use Fifa\ConnectId\Sdk\Model\PersonDetailsRequest;
use Fifa\ConnectId\Sdk\Registration\ValidationException;
use Fifa\ConnectId\Sdk\Util\Builder\Error\CompositeErrorBuilder;
use Fifa\ConnectId\Sdk\Util\Data\Message\ActionType;
use Fifa\ConnectId\Sdk\Util\Data\Message\MessageProperties;
use Fifa\ConnectId\Sdk\Util\StringUtils;
use Fifa\ConnectServiceBus\Sdk\Exception\FifaConnectServiceBusSdkException;
use Fifa\ConnectServiceBus\Sdk\Message\Message;

class PersonDetailsRequestMessageHandler implements MessageHandlerInterface
{
    /**
     * @var callable
     */
    private $personDetailsRequestHandler;

    /**
     * @var callable
     */
    private $exceptionHandler;

    public function __construct(callable $personDetailsRequestHandler, callable $exceptionHandler)
    {
        $this->personDetailsRequestHandler = $personDetailsRequestHandler;
        $this->exceptionHandler = $exceptionHandler;
    }

    public function canHandle(?string $messageType): bool
    {
        return $messageType == ActionType::PERSON_DETAILS_REQUEST;
    }

    /**
     * @noinspection PhpRedundantCatchClauseInspection
     * @throws ValidationException
     */
    public function handle(?string $messageType, Message $message)
    {
        $replyTo = $message->getReplyTo();
        $uniqueFifaId = $message->getPropertyIfExists(MessageProperties::UNIQUE_FIFA_ID);
        $correlationId = $message->getPropertyIfExists(MessageProperties::CORRELATION_ID);

        $errorBuilder = new CompositeErrorBuilder();
        $errors = $errorBuilder
            ->addMessageForCase(StringUtils::isNullOrEmpty($replyTo), 'The "'.Message::REPLY_TO_KEY.'" property cannot be null or empty in a person details request message.')
            ->addMessageForCase(StringUtils::isNullOrEmpty($uniqueFifaId), 'The "'.MessageProperties::UNIQUE_FIFA_ID.'" property cannot be null or empty in a person details request message.')
            ->addMessageForCase(StringUtils::isNullOrEmpty($correlationId), 'The "'.MessageProperties::CORRELATION_ID.'" property cannot be null or empty in a person details request message.')
            ->build();

        if (!is_null($errors)) {
            throw new ValidationException($errors);
        }

        try {
            $personDetailsRequest = new PersonDetailsRequest($replyTo, $uniqueFifaId, $correlationId, $message);
            call_user_func_array($this->personDetailsRequestHandler, [$personDetailsRequest]);
        } catch (FifaConnectServiceBusSdkException $e) {
            call_user_func_array($this->exceptionHandler, [$e]);
        }
    }

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