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

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

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

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

    /**
     * @param ApiException $e
     * @param BadRequestResponseType $responseType
     * @return string
     */
    private function formatMessage(ApiException $e, BadRequestResponseType $responseType): string
    {
        $message = $responseType->getMessage();
        if (substr($message, strlen($message) - 1, strlen($message)) === '.') {
            $message = substr($message, 0, strlen($message) - 1);
        }

        $message = sprintf('The service responded with a status code %s. %s. ', $e->getCode(), $message);
        $message .= implode('; ', array_map(
            function(DetailsItemType $details) {
                return $details->getValue();
            },
            $responseType->getDetails()
        ));

        return trim($message);
    }

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