"""Has the client even opened it?

The most common anxiety in this workflow, and until now nothing in easel could
answer it though the data was one column away.
"""

from tests.conftest import as_user
from tests.test_domain import add_screen_option, make_project


def test_a_heartbeat_records_that_someone_is_looking(client, kit):
    iid = make_project(client, kit)
    add_screen_option(client, iid)

    as_user(client, "cleo")
    assert client.post(f"/api/projects/{iid}/heartbeat").status_code == 200

    as_user(client, "mara")
    people = {p["username"]: p for p in
              client.get(f"/api/projects/{iid}/who").json()["people"]}
    assert "cleo" in people
    assert people["cleo"]["last_active_at"] is not None


def test_the_roster_is_the_client_side_only(client, kit):
    """It answers a question about the client. We are not looking for ourselves,
    and nate — granted elsewhere — is not on this project at all."""
    iid = make_project(client, kit)
    add_screen_option(client, iid)
    people = [p["username"] for p in
              client.get(f"/api/projects/{iid}/who").json()["people"]]
    assert people == ["cleo"]


def test_a_heartbeat_does_not_clear_what_is_new(client, kit):
    """The reason last_active_at is its own column. A heartbeat sharing the
    newness marker would silently clear "new since your last visit" flags out
    from under someone who had not scrolled to them yet."""
    iid = make_project(client, kit)
    sid, _oid = add_screen_option(client, iid)
    as_user(client, "cleo")
    client.post(f"/api/projects/{iid}/seen")

    as_user(client, "mara")
    client.post(f"/api/screens/{sid}/options", json={"title": "Two", "concept_tag": ""})

    as_user(client, "cleo")
    assert client.get(f"/api/projects/{iid}").json()["new_count"] >= 1
    client.post(f"/api/projects/{iid}/heartbeat")
    assert client.get(f"/api/projects/{iid}").json()["new_count"] >= 1


def test_a_first_heartbeat_does_not_swallow_a_first_visit(client, kit):
    """Seeding the seen-marker at "now" would mean a client whose first action
    was a heartbeat never saw a single new flag afterwards."""
    iid = make_project(client, kit)
    sid, _oid = add_screen_option(client, iid)
    as_user(client, "cleo")
    client.post(f"/api/projects/{iid}/heartbeat")

    as_user(client, "mara")
    client.post(f"/api/screens/{sid}/options", json={"title": "Two", "concept_tag": ""})
    as_user(client, "cleo")
    assert client.get(f"/api/projects/{iid}").json()["new_count"] >= 1


def test_the_client_cannot_see_who_else_is_looking(client, kit):
    iid = make_project(client, kit)
    add_screen_option(client, iid)
    as_user(client, "cleo")
    assert client.get(f"/api/projects/{iid}/who").status_code == 403


def test_an_outsider_cannot_heartbeat_a_board(client, kit):
    iid = make_project(client, kit)
    add_screen_option(client, iid)
    as_user(client, "nate")
    assert client.post(f"/api/projects/{iid}/heartbeat").status_code == 404
