<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Tenant;

use Override;

/**
 * In-memory implementation of TenantRegistry.
 * Useful for tests and development environments.
 */
final class InMemoryTenantRegistry implements TenantRegistry
{
    /** @var array<string, TenantConfig> Indexed by tenant ID */
    private array $byId = [];

    /** @var array<string, TenantConfig> Indexed by subdomain */
    private array $bySubdomain = [];

    /**
     * @param TenantConfig[] $configs
     */
    public function __construct(array $configs)
    {
        foreach ($configs as $config) {
            $this->byId[(string) $config->tenantId] = $config;
            $this->bySubdomain[$config->subdomain] = $config;
        }
    }

    #[Override]
    public function getConfig(TenantId $tenantId): TenantConfig
    {
        $key = (string) $tenantId;

        if (!isset($this->byId[$key])) {
            throw TenantNotFoundException::withId($tenantId);
        }

        return $this->byId[$key];
    }

    #[Override]
    public function getBySubdomain(string $subdomain): TenantConfig
    {
        if (!isset($this->bySubdomain[$subdomain])) {
            throw TenantNotFoundException::withSubdomain($subdomain);
        }

        return $this->bySubdomain[$subdomain];
    }

    #[Override]
    public function exists(string $subdomain): bool
    {
        return isset($this->bySubdomain[$subdomain]);
    }

    #[Override]
    public function getAllConfigs(): array
    {
        return array_values($this->byId);
    }
}
