<?php

declare(strict_types=1);

namespace Blax\WebRtc\Rooms;

use Blax\WebRtc\Contracts\RoomRegistry;

/**
 * A {@see RoomRegistry} backed by a declarative array (from `config('webrtc.rooms')`):
 *
 *   'lobby'        => ['mode' => 'sfu', 'limit' => 50, 'type' => 'presence'],
 *   'just-talk'    => ['mode' => 'p2p', 'limit' => 20],
 *   'private-desk' => ['mode' => 'p2p'],           // type inferred from the id prefix
 *
 * A bare value is also accepted as shorthand for the mode: `'just-talk' => 'p2p'`.
 */
final class ConfigRoomRegistry implements RoomRegistry
{
    /** @var array<string,RoomDefinition> */
    private array $rooms;

    /** @param array<string,mixed> $rooms */
    public function __construct(array $rooms)
    {
        $this->rooms = [];
        foreach ($rooms as $id => $config) {
            $id = (string) $id;
            $this->rooms[$id] = is_array($config)
                ? RoomDefinition::fromConfig($id, $config)
                : new RoomDefinition($id, RoomMode::fromString(is_string($config) ? $config : null));
        }
    }

    public function has(string $roomId): bool
    {
        return isset($this->rooms[$roomId]);
    }

    public function get(string $roomId): ?RoomDefinition
    {
        return $this->rooms[$roomId] ?? null;
    }

    public function mode(string $roomId): ?RoomMode
    {
        return $this->rooms[$roomId]?->mode;
    }

    public function all(): array
    {
        return $this->rooms;
    }
}
