"""NaverClient.fetch_articles — httpx 경로 (respx). acquire_token은 실브라우저라 제외."""
import httpx
import pytest
import respx

from naver_client import NaverClient

API = "https://new.land.naver.com/api/articles"


def _client():
    return NaverClient(real_estate_type="APT:ABYG", token_url="https://x", headless=True)


async def test_fetch_requires_token():
    c = _client()
    with pytest.raises(RuntimeError):
        await c.fetch_articles("1159010100", 1)
    await c.close()


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

    def _resp(request):
        captured["auth"] = request.headers.get("authorization")
        captured["cookie"] = request.headers.get("cookie")
        captured["url"] = str(request.url)
        return httpx.Response(200, json={
            "isMoreData": True,
            "articleList": [{"articleNo": "111", "articleName": "테스트아파트"}]})

    respx.get(API).mock(side_effect=_resp)
    c = _client()
    c._token = "Bearer TESTJWT"          # acquire_token 우회(단위테스트)
    c._cookies = "NNB=abc; page_uid=xyz"
    out = await c.fetch_articles("1159010100", page=2)
    assert out["articleList"][0]["articleNo"] == "111"
    assert captured["auth"] == "Bearer TESTJWT"
    assert captured["cookie"] == "NNB=abc; page_uid=xyz"
    assert "cortarNo=1159010100" in captured["url"]
    assert "page=2" in captured["url"]
    assert "realEstateType=APT" in captured["url"]
    await c.close()


@respx.mock
async def test_fetch_non_200_raises():
    respx.get(API).mock(return_value=httpx.Response(429, json={"code": "TOO_MANY_REQUESTS"}))
    c = _client()
    c._token = "Bearer X"
    with pytest.raises(httpx.HTTPStatusError):
        await c.fetch_articles("1159010100", 1)
    await c.close()
