import json

import httpx
import pytest

from beaver.memory.gateway import MemoryGatewayClient, MemoryGatewayUserStore


@pytest.mark.asyncio
async def test_memory_gateway_client_uses_cached_user_key(tmp_path) -> None:
    store = MemoryGatewayUserStore(tmp_path / "gateway.db")
    store.save_user_key("user-1", "cached-key")
    requests: list[httpx.Request] = []

    async def handler(request: httpx.Request) -> httpx.Response:
        requests.append(request)
        return httpx.Response(500, json={"error": "should not be called"})

    client = MemoryGatewayClient(
        base_url="http://gateway.test",
        store=store,
        transport=httpx.MockTransport(handler),
    )

    user_key = await client.ensure_user("user-1")

    assert user_key == "cached-key"
    assert requests == []


@pytest.mark.asyncio
async def test_memory_gateway_client_creates_and_caches_user_key(tmp_path) -> None:
    store = MemoryGatewayUserStore(tmp_path / "gateway.db")
    requests: list[httpx.Request] = []

    async def handler(request: httpx.Request) -> httpx.Response:
        requests.append(request)
        assert request.method == "POST"
        assert request.url.path == "/memory-system/users"
        assert json.loads(request.content) == {"user_id": "user-1"}
        return httpx.Response(
            200,
            json={
                "status": "success",
                "account": {
                    "status": "ok",
                    "result": {"user_key": "created-key"},
                },
            },
        )

    client = MemoryGatewayClient(
        base_url="http://gateway.test",
        store=store,
        transport=httpx.MockTransport(handler),
    )

    user_key = await client.ensure_user("user-1")

    assert user_key == "created-key"
    assert store.get_user_key("user-1") == "created-key"
    assert len(requests) == 1


@pytest.mark.asyncio
async def test_memory_gateway_client_ingests_messages_with_user_key(tmp_path) -> None:
    store = MemoryGatewayUserStore(tmp_path / "gateway.db")
    requests: list[httpx.Request] = []

    async def handler(request: httpx.Request) -> httpx.Response:
        requests.append(request)
        assert request.method == "POST"
        assert request.url.path == "/memory-system/messages"
        assert request.headers["X-API-Key"] == "gateway-api-key"
        assert json.loads(request.content) == {
            "user_id": "user-1",
            "user_key": "user-key",
            "session_id": "session-1",
            "user_message": "hello",
            "assistant_message": "hi",
        }
        return httpx.Response(200, json={"status": "success", "message_count": 2})

    client = MemoryGatewayClient(
        base_url="http://gateway.test",
        api_key="gateway-api-key",
        store=store,
        transport=httpx.MockTransport(handler),
    )

    result = await client.ingest_messages(
        user_id="user-1",
        user_key="user-key",
        session_id="session-1",
        user_message="hello",
        assistant_message="hi",
    )

    assert result["status"] == "success"
    assert len(requests) == 1
