# retoor <retoor@molodetz.nl>

import time

import requests

from tests.api.battles._helpers import _create_war_post, _fight, _join, _session_battles
from tests.conftest import BASE_URL


def test_events_ordered_and_incremental(app_server):
    s, _ = _session_battles()
    other, _ = _session_battles()
    _, war = _create_war_post(s, f"events-{int(time.time() * 1000)}")
    _join(s, war["uid"], "a")
    _join(other, war["uid"], "b")
    _fight(s, war["uid"])

    r = requests.get(f"{BASE_URL}/battles/{war['uid']}/events")
    assert r.status_code == 200
    payload = r.json()
    assert payload["status"] == "active"
    seqs = [event["seq"] for event in payload["events"]]
    assert seqs == sorted(seqs)
    kinds = [event["kind"] for event in payload["events"]]
    assert kinds[:3] == ["join", "join", "fight"]
    assert "lead_change" in kinds

    fight_event = next(e for e in payload["events"] if e["kind"] == "fight")
    assert fight_event["faction"] == "a"
    assert fight_event["hp_a"] > 0

    after = seqs[1]
    r = requests.get(
        f"{BASE_URL}/battles/{war['uid']}/events", params={"after": after}
    )
    replay = [event["seq"] for event in r.json()["events"]]
    assert replay == [seq for seq in seqs if seq > after]


def test_events_unknown_battle_404(app_server):
    r = requests.get(f"{BASE_URL}/battles/nope/events")
    assert r.status_code == 404
