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

use Fifa\ConnectServiceBus\Sdk\Api\ApiException;
use Fifa\ConnectServiceBus\Sdk\Api\Model\BadRequestResponseType;
use Fifa\ConnectServiceBus\Sdk\Api\Model\DetailsItemType;

/**
 * Class InvalidClientDataException
 * @package Fifa\ConnectServiceBus\Sdk\Exception
 */
class InvalidClientDataException extends FifaConnectServiceBusSdkException
{
    /**
     * @var BadRequestResponseType
     */
    private $badRequestResponse;

    /**
     * Constructor
     *
     * @param ApiException $apiException
     * @param BadRequestResponseType $badRequestResponseType
     */
    public function __construct(ApiException $apiException, BadRequestResponseType $badRequestResponseType)
    {
        $this->badRequestResponse = $badRequestResponseType;
        parent::__construct($apiException, $this->formatMessage($apiException, $badRequestResponseType));
    }

    /**
     * Gets response for bad request
     *
     * @return BadRequestResponseType
     */
    public function getBadRequestResponse(): BadRequestResponseType
    {
        return $this->badRequestResponse;
    }

    /**
     * Gets details as an array
     *
     * @return DetailsItemType[]
     */
    public function getDetails(): array
    {
        $details = $this->getBadRequestResponse()->getDetails();

        return is_array($details) ? $details : array();
    }

    /**
     * @param ApiException $e
     * @param BadRequestResponseType $duplicatesResponseType
     * @return string
     */
    private function formatMessage(ApiException $e, BadRequestResponseType $duplicatesResponseType): string
    {
        $message = sprintf('The service responded with a status code %s. %s: ', $e->getCode(), $duplicatesResponseType->getMessage());

        $message .= implode(
            ', ',
            array_map(
                function(DetailsItemType $details) {
                    return $details->getValue();
                },
                $this->getDetails()
            )
        );

        return $message;
    }
}