"""Server list in-memory sort after Redis overlay."""
from datetime import datetime, timezone

from server.application.services.server_list_sort import sort_server_items


def _item(
    *,
    name: str = "srv",
    status: str = "unknown",
    last_heartbeat: str | None = None,
    agent_version: str | None = None,
) -> dict:
    return {
        "name": name,
        "status": status,
        "last_heartbeat": last_heartbeat,
        "agent_version": agent_version,
    }


def test_status_sort_asc():
    items = [
        _item(name="c", status="unknown"),
        _item(name="a", status="online"),
        _item(name="b", status="offline"),
    ]
    sorted_items = sort_server_items(items, "status", "asc")
    assert [i["status"] for i in sorted_items] == ["online", "offline", "unknown"]


def test_status_sort_desc():
    items = [
        _item(name="a", status="online"),
        _item(name="b", status="offline"),
        _item(name="c", status="unknown"),
    ]
    sorted_items = sort_server_items(items, "status", "desc")
    assert [i["status"] for i in sorted_items] == ["unknown", "offline", "online"]


def test_heartbeat_sort_uses_overlay_not_db_order():
    old = _item(name="old", last_heartbeat="2026-01-01T00:00:00+00:00")
    new = _item(name="new", last_heartbeat="2026-06-08T12:00:00+00:00")
    items = [old, new]
    sorted_items = sort_server_items(items, "heartbeat", "desc")
    assert sorted_items[0]["name"] == "new"
    assert sorted_items[1]["name"] == "old"


def test_heartbeat_nulls_last_asc_and_desc():
    items = [
        _item(name="with", last_heartbeat="2026-06-01T00:00:00+00:00"),
        _item(name="empty", last_heartbeat=None),
    ]
    asc = sort_server_items(items, "heartbeat", "asc")
    assert asc[0]["name"] == "with"
    assert asc[-1]["name"] == "empty"
    desc = sort_server_items(items, "heartbeat", "desc")
    assert desc[0]["name"] == "with"
    assert desc[-1]["name"] == "empty"


def test_agent_version_empty_last():
    items = [
        _item(name="b", agent_version="2.1.0"),
        _item(name="a", agent_version=""),
        _item(name="c", agent_version="1.0.0"),
    ]
    asc = sort_server_items(items, "agent_version", "asc")
    assert asc[0]["name"] == "c"
    assert asc[1]["name"] == "b"
    assert asc[-1]["name"] == "a"


def test_heartbeat_parse_z_suffix():
    ts = datetime(2026, 6, 8, 12, 0, tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
    items = [
        _item(name="early", last_heartbeat="2026-01-01T00:00:00+00:00"),
        _item(name="late", last_heartbeat=ts),
    ]
    sorted_items = sort_server_items(items, "heartbeat", "desc")
    assert sorted_items[0]["name"] == "late"
