<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\Environment;
use Magento\Framework\Controller\Result\Json;

class JsonUrl
{
    private Environment $environment;

    public function __construct(Environment $environment)
    {
        $this->environment = $environment;
    }

    public function beforeSetData(Json $subject, $data, $cycleCheck = false, $options = []): array
    {
        if (is_array($data) && isset($data['url']) && is_string($data['url'])
            && strpos($data['url'], Environment::VENDOR_ORIGIN . '/') === 0
        ) {
            if (strpos($data['url'], Environment::VENDOR_ORIGIN . '/calculator/') === 0) {
                $this->environment->assertUatCredentials();
            }
            $data['url'] = $this->environment->replaceVendorOrigin($data['url']);
        }
        return [$data, $cycleCheck, $options];
    }
}
