<?php
/**
 *
 * Adyen Payment module (https://www.adyen.com/)
 *
 * Copyright (c) 2021 Adyen NV (https://www.adyen.com/)
 * See LICENSE.txt for license details.
 *
 * Author: Adyen <magento@adyen.com>
 */

namespace Adyen\Payment\Gateway\Request;

use Adyen\Payment\Helper\ReturnUrlHelper;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Payment\Gateway\Data\PaymentDataObject;
use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Request\BuilderInterface;
use Magento\Sales\Model\Order;
use Magento\Store\Model\StoreManagerInterface;

class ReturnUrlDataBuilder implements BuilderInterface
{
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var ReturnUrlHelper
     */
    private $returnUrlHelper;

    /**
     * CheckoutDataBuilder constructor.
     *
     * @param ReturnUrlHelper $returnUrlHelper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ReturnUrlHelper $returnUrlHelper,
        StoreManagerInterface $storeManager
    ) {
        $this->returnUrlHelper = $returnUrlHelper;
        $this->storeManager = $storeManager;
    }

    /**
     * @param array $buildSubject
     * @return array
     * @throws NoSuchEntityException
     */
    public function build(array $buildSubject): array
    {
        /** @var PaymentDataObject $paymentDataObject */
        $paymentDataObject = SubjectReader::readPayment($buildSubject);
        $payment = $paymentDataObject->getPayment();
        /** @var Order $order */
        $order = $payment->getOrder();
        $merchantReference = $order->getIncrementId();
        $customReturnUrl = $payment->getAdditionalInformation('returnUrl');

        if (!empty($customReturnUrl)) {
            $returnUrl = strtr($customReturnUrl, [
                ':merchantReference' => $merchantReference
            ]);
        } else {
            $returnUrl = $this->returnUrlHelper->getStoreReturnUrl($this->storeManager->getStore()->getId())
                . '?merchantReference=' . $merchantReference;
        }

        return [
            'body' => [
                'returnUrl' => $returnUrl
            ]
        ];
    }
}
