"""NASClient — targets/ingest + X-Internal-Key (respx)."""
import json as _json

import httpx
import respx

from nas_client import NASClient

BASE = "http://nas.test"


@respx.mock
async def test_get_targets_sends_key():
    route = respx.get(f"{BASE}/api/internal/realestate/targets").mock(
        return_value=httpx.Response(200, json={
            "dongs": [{"dong": "신대방동", "cortar_no": "1159010100"}],
            "deal_types": ["전세", "매매"], "page_limit": 2}))
    c = NASClient(BASE, "KEY")
    tg = await c.get_targets()
    assert tg["page_limit"] == 2
    assert tg["dongs"][0]["cortar_no"] == "1159010100"
    assert route.calls.last.request.headers["X-Internal-Key"] == "KEY"
    await c.close()


@respx.mock
async def test_post_ingest_payload():
    captured = {}

    def _resp(request):
        captured.update(_json.loads(request.content))
        return httpx.Response(200, json={"received": 3, "new": 2, "matched": 1})

    respx.post(f"{BASE}/api/internal/realestate/listings-ingest").mock(side_effect=_resp)
    c = NASClient(BASE, "KEY")
    batches = [{"dong": "신대방동", "articles": [{"articleNo": "1"}, {"articleNo": "2"}]}]
    out = await c.post_ingest("2026-07-10T05:00:00Z", batches)
    assert out == {"received": 3, "new": 2, "matched": 1}
    assert captured["fetched_at"] == "2026-07-10T05:00:00Z"
    assert captured["batches"] == batches
    await c.close()
