<?php

namespace Fifa\ConnectId\Sdk\MessageHandlers;

use Fifa\ConnectId\Sdk\Model\PersonDetails;
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\Message\Message;

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

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

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

    /**
     * @throws ValidationException
     */
    public function handle(?string $messageType, Message $message)
    {
        $sender = $message->getSender();
        $correlationId = $message->getPropertyIfExists(MessageProperties::CORRELATION_ID);

        $errorBuilder = new CompositeErrorBuilder();
        $errors = $errorBuilder
            ->addMessageForCase(StringUtils::isNullOrEmpty($sender), 'The "'.Message::SENDER_KEY.'" 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);
        }

        $senderChunks = explode('_', $sender);
        $xmlData = strlen($message->getContent()) === 0 ? null : $message->getContent();
        $personDetails = new PersonDetails($senderChunks[0], $xmlData, $correlationId);
        call_user_func_array($this->handler, [$personDetails]);
    }

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