<?php

namespace Fifa\ConnectId\Sdk\Registration;

use Fifa\ConnectId\Sdk\Util\CorrelationIdFormatter;
use Fifa\ConnectId\Sdk\Util\Data\Message\ActionType;
use Fifa\ConnectId\Sdk\Util\Data\Message\MessageProperties;
use Fifa\ConnectId\Sdk\Util\SdkVersionHelper;
use Fifa\ConnectServiceBus\Sdk\Exception\FifaConnectServiceBusSdkException;
use Fifa\ConnectServiceBus\Sdk\FifaConnectServiceBusClientInterface;
use Fifa\ConnectServiceBus\Sdk\Message\Message;
use Psr\Log\LoggerInterface;

// This class was extracted to keep this SDK in sync with the .NET and Java one.
// Waiting for responses was removed due to the lack of Tasks in Java & PHP
class PersonDetailsMessageExchanger
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var FifaConnectServiceBusClientInterface
     */
    private $serviceBusClient;

    /**
     * @var string
     */
    private $sdkVersion;

    /**
     * Constructor
     *
     * @param FifaConnectServiceBusClientInterface $serviceBusClient
     * @param LoggerInterface $logger
     */
    public function __construct(FifaConnectServiceBusClientInterface $serviceBusClient, LoggerInterface $logger) {
        $this->serviceBusClient = $serviceBusClient;
        $this->logger = $logger;
        $this->sdkVersion = SdkVersionHelper::getSdkVersion();
    }

    /**
     * @param string $uniqueFifaId
     * @param string $recipient
     * @param string $correlationId
     *
     * @throws FifaConnectServiceBusSdkException
     */
    public function sendRequestForPersonDetails(string $uniqueFifaId, string $recipient, string $correlationId) {
        $this->logger->debug(sprintf(CorrelationIdFormatter::format($correlationId) . 'Sending a request for details of `%s` to organisation `%s`.', $uniqueFifaId, $recipient));
        $this->createAndSendPersonDetailsMessage($uniqueFifaId, $recipient, $correlationId);
        $this->logger->debug(sprintf(CorrelationIdFormatter::format($correlationId) . 'Sent a request for details of `%s` to organisation `%s`.', $uniqueFifaId, $recipient));
    }

    /**
     * @param string $uniqueFifaId
     * @param string $recipient
     * @param string $correlationId
     *
     * @throws FifaConnectServiceBusSdkException
     */
    private function createAndSendPersonDetailsMessage(string $uniqueFifaId, string $recipient, string $correlationId)
    {
        $properties = array(
            MessageProperties::UNIQUE_FIFA_ID => $uniqueFifaId,
            MessageProperties::CORRELATION_ID => $correlationId,
            MessageProperties::VERSION => $this->sdkVersion
        );

        $messageContent = ' ';
        $message = new Message($messageContent, ActionType::PERSON_DETAILS_REQUEST, $properties);
        $this->serviceBusClient->send($recipient, $message);
    }
}