from __future__ import annotations

import asyncio

import pytest

from cliproom.protocol import ProtocolValidationError
from cliproom.server.session_manager import ClientConnection, SessionManager


class _DummyWriter:
    def write(self, payload: bytes) -> None:
        _ = payload

    async def drain(self) -> None:
        return


def _conn(name: str) -> ClientConnection:
    return ClientConnection(client_name=name, writer=_DummyWriter())  # type: ignore[arg-type]


def test_join_and_discoverable_sessions() -> None:
    async def scenario() -> None:
        mgr = SessionManager()
        c1 = _conn("a")
        c2 = _conn("b")
        s = await mgr.join("devteam", "h1", c1)
        assert s.name == "devteam"
        await mgr.join("support", "h2", c2)
        sessions = await mgr.list_discoverable_sessions()
        assert ("devteam", True) in sessions
        assert ("support", True) in sessions

    asyncio.run(scenario())


def test_invalid_auth_rejected() -> None:
    async def scenario() -> None:
        mgr = SessionManager()
        await mgr.join("devteam", "h1", _conn("a"))
        with pytest.raises(ProtocolValidationError):
            await mgr.join("devteam", "h2", _conn("b"))

    asyncio.run(scenario())
