<?php
namespace Fifa\ConnectServiceBus\Sdk\Authentication;

use UnexpectedValueException;

/**
 * Class AuthenticationResourceBuilder
 * @package Fifa\ConnectServiceBus\Sdk\Authentication
 */
abstract class AuthenticationResourceBuilderBase implements AuthenticationResourceBuilderInterface
{
    /**
     * @var array
     */
    private $mapping;

    /**
     * Constructor
     * @param array $mapping
     */
    protected function __construct(array $mapping)
    {
        $this->mapping = $mapping;
    }

    /**
     * Returns resource Uri string
     *
     * @param string $serviceUri
     * @param string $tenant
     * @return string
     * @throws UnexpectedValueException
     */
    public function buildResourceUri(string $serviceUri, string $tenant): string
    {
        if (strpos($serviceUri, 'http') !== 0) {
            $serviceUri = 'http://' . $serviceUri;
        }

        $uriParsed = parse_url($serviceUri);
        $host = $uriParsed['host'] ?? $uriParsed['path'];

        if (!isset($this->mapping[$host])) {
            throw new UnexpectedValueException('Provided mapping array doesn\'t contain key: ' . $host);
        }

        return 'https://' . $tenant . '/' . $this->mapping[$host];
    }
}