<?php

declare(strict_types=1);

namespace ComerciaGlobalPayments\AddonPayments\SDK\Response;

use GuzzleHttp\Exception\TransferException;

/**
 * Class ExpressCheckout.
 *
 * Models express checkout response.
 */
class ExpressCheckout extends AbstractResponse
{
    /**
     * @var \ComerciaGlobalPayments\AddonPayments\SDK\Response\PaymentSolution[]
     */
    protected $paymentSolutions;

    /**
     * ExpressCheckout constructor.
     *
     * @param \GuzzleHttp\Message\ResponseInterface|\Psr\Http\Message\ResponseInterface $httpResponse
     */
    public function __construct($httpResponse)
    {
        // @TODO: Add a custom exceptions
        $this->httpResponse = $httpResponse;
        if (null === $httpResponse->getBody()) {
            throw new TransferException('The API response is empty');
        }

        $this->responseData = json_decode($httpResponse->getBody()->getContents(), false);

        if (empty($this->responseData) || \JSON_ERROR_NONE !== json_last_error()) {
            throw new TransferException('The API response does not contains a valid JSON data');
        }

        if (!\is_array($this->responseData->paymentSolutions) || empty($this->responseData->paymentSolutions)) {
            throw new TransferException('The API response does not contains a valid payload');
        }

        foreach ($this->responseData->paymentSolutions as $object) {
            $this->paymentSolutions[] = new PaymentSolution($object);
        }
    }

    /**
     * @return \ComerciaGlobalPayments\AddonPayments\SDK\Response\PaymentSolution[]
     */
    public function getPaymentSolutions(): array
    {
        return $this->paymentSolutions;
    }
}
