from __future__ import annotations

import asyncio

import app.db as db_mod  # type: ignore


def _append(event: str, *, chat_id: str, operator_id: str = "op-a", status: str = "ok", node_id: str = "NODA2"):
    return asyncio.run(
        db_mod.append_audit_event(
            event=event,
            operator_id=operator_id,
            chat_id=chat_id,
            node_id=node_id,
            agent_id="sofiia",
            status=status,
            data={"tag": event},
        )
    )


def test_audit_read_cursor_pagination(sofiia_client, monkeypatch):
    monkeypatch.setenv("SOFIIA_CONSOLE_API_KEY", "audit-secret")
    headers = {"X-API-Key": "audit-secret"}
    chat_id = "chat:NODA2:sofiia:web:audit-read"
    for i in range(5):
        _append("chat.send.result", chat_id=chat_id, operator_id=f"op-{i}")

    r1 = sofiia_client.get(f"/api/audit?chat_id={chat_id}&limit=2", headers=headers)
    assert r1.status_code == 200, r1.text
    j1 = r1.json()
    assert len(j1["items"]) == 2
    assert j1["has_more"] is True
    assert j1["next_cursor"]

    r2 = sofiia_client.get(f"/api/audit?chat_id={chat_id}&limit=2&cursor={j1['next_cursor']}", headers=headers)
    assert r2.status_code == 200, r2.text
    j2 = r2.json()
    assert len(j2["items"]) >= 1
    ids_1 = {x["id"] for x in j1["items"]}
    ids_2 = {x["id"] for x in j2["items"]}
    assert ids_1.isdisjoint(ids_2)


def test_audit_read_filter_by_event(sofiia_client, monkeypatch):
    monkeypatch.setenv("SOFIIA_CONSOLE_API_KEY", "audit-secret")
    headers = {"X-API-Key": "audit-secret"}
    chat_id = "chat:NODA2:sofiia:web:audit-filter"
    _append("chat.send.error", chat_id=chat_id, status="error")
    _append("chat.send.result", chat_id=chat_id, status="ok")
    _append("chat.create", chat_id=chat_id, status="ok")

    r = sofiia_client.get("/api/audit?event=chat.send.error&limit=50", headers=headers)
    assert r.status_code == 200, r.text
    items = r.json()["items"]
    assert items, "Expected at least one audit item for event filter"
    assert all((it.get("event") == "chat.send.error") for it in items)
