import httpx
import pytest

from near_fastapi.models import Network
from near_fastapi.near_client import NearRPCClient, NearRPCError


@pytest.mark.asyncio
async def test_view_function_decodes_json(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_post(self, url: str, json: dict):
        class _Resp:
            def raise_for_status(self) -> None:
                return None

            def json(self) -> dict:
                return {
                    "result": {
                        "block_height": 1,
                        "block_hash": "abc",
                        "logs": [],
                        "result": [123, 34, 111, 107, 34, 58, 116, 114, 117, 101, 125],
                    }
                }

        return _Resp()

    monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)
    client = NearRPCClient()
    out = await client.view_function(
        account_id="social.near",
        method_name="get",
        args={"k": "v"},
        network=Network.mainnet,
    )
    assert out["decoded_result"] == {"ok": True}


@pytest.mark.asyncio
async def test_rpc_error_raised(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fake_post(self, url: str, json: dict):
        class _Resp:
            def raise_for_status(self) -> None:
                return None

            def json(self) -> dict:
                return {"error": {"message": "boom"}}

        return _Resp()

    monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)
    client = NearRPCClient()

    with pytest.raises(NearRPCError):
        await client.network_status(Network.mainnet)
