# retoor <retoor@molodetz.nl>

from devplacepy.config import PRESENCE_ONLINE_LIMIT
from devplacepy.services.presence_relay import ROSTER_TOPIC, roster_payload


def _rows(count):
    return [
        {"uid": f"u{index:03d}", "username": f"user{index:03d}", "avatar_seed": None}
        for index in range(count)
    ]


def test_roster_topic_is_the_single_presence_channel():
    assert ROSTER_TOPIC == "public.presence.roster"


def test_payload_only_carries_the_online_set(local_db):
    rows = _rows(4)
    payload = roster_payload(rows, {"u000", "u002"})
    assert payload["online"] == ["u000", "u002"]
    assert [user["uid"] for user in payload["users"]] == ["u000", "u002"]
    assert payload["count"] == 2


def test_dots_and_display_roster_come_from_one_set(local_db):
    rows = _rows(PRESENCE_ONLINE_LIMIT + 7)
    online = {row["uid"] for row in rows}
    payload = roster_payload(rows, online)
    # every online user is authoritative for their avatar dot...
    assert set(payload["online"]) == online
    # ...while the feed's avatar panel stays capped for display
    assert len(payload["users"]) == PRESENCE_ONLINE_LIMIT
    assert payload["count"] == PRESENCE_ONLINE_LIMIT
    assert set(payload["online"]) >= {user["uid"] for user in payload["users"]}


def test_avatar_seed_falls_back_to_username(local_db):
    payload = roster_payload([{"uid": "u1", "username": "ada", "avatar_seed": None}], {"u1"})
    assert payload["users"][0]["avatar_seed"] == "ada"


def test_offline_users_are_absent_everywhere(local_db):
    payload = roster_payload(_rows(3), set())
    assert payload == {"count": 0, "online": [], "users": []}
