<?php

namespace Autogedal\TbiBank\Plugin;

use Autogedal\TbiBank\Model\Environment;

class FrontendUrls
{
    private Environment $environment;

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

    public function afterGetOrigin($subject, $result): string
    {
        return $this->replaceEncoded((string) $result);
    }

    public function afterGetCalculatorUrl($subject, $result): string
    {
        $this->environment->assertUatCredentials();
        return $this->replaceEncoded((string) $result);
    }

    public function afterGetAllowedOrigin($subject, $result): string
    {
        return $this->environment->replaceVendorOrigin((string) $result);
    }

    private function replaceEncoded(string $value): string
    {
        $decoded = base64_decode($value, true);
        return $decoded === false ? $value : base64_encode($this->environment->replaceVendorOrigin($decoded));
    }
}
