<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Tenant;

use App\Shared\Domain\Tenant\TenantId as DomainTenantId;

/**
 * Builds tenant-aware URLs using the tenant subdomain and base domain.
 */
final readonly class TenantUrlBuilder
{
    public function __construct(
        private TenantRegistry $tenantRegistry,
        private string $appUrl,
        private string $baseDomain,
    ) {
    }

    public function build(DomainTenantId $tenantId, string $path): string
    {
        $tenantConfig = $this->tenantRegistry->getConfig(
            TenantId::fromString((string) $tenantId),
        );

        $parsed = parse_url($this->appUrl);
        $scheme = $parsed['scheme'] ?? 'https';
        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';

        return $scheme . '://' . $tenantConfig->subdomain . '.' . $this->baseDomain . $port . $path;
    }
}
