"""AvartenRestClient and the PHP-serialized reader, fully offline."""
import pytest

from integrations.avarten import rest_client
from integrations.avarten.php_serialized import PhpSerializedError, php_unserialize
from integrations.avarten.rest_client import AvartenRestClient, AvartenRestError
from tests.avarten.avarten_rest_fixtures import (
    FakeResponse,
    FakeSession,
    additional_features,
    connection_error,
    media_record,
    rest_property,
)

PROPS = rest_client.PROPERTIES_ENDPOINT
MEDIA = rest_client.MEDIA_ENDPOINT


def _client(handler):
    session = FakeSession(handler)
    return AvartenRestClient(session=session), session


# ---------------------------------------------------------------- listing

def test_list_properties_single_page_sends_fields_and_page_size():
    records = [rest_property(id=1), rest_property(id=2)]
    client, session = _client(lambda path, params: FakeResponse(records, headers={"X-WP-TotalPages": "1"}))

    result = client.list_properties(fields="id,slug")

    assert [record["id"] for record in result] == [1, 2]
    assert session.calls == [(PROPS, {"per_page": 100, "page": 1, "_fields": "id,slug"})]


def test_list_properties_follows_pagination_header():
    pages = {1: [rest_property(id=1)], 2: [rest_property(id=2)], 3: [rest_property(id=3)]}
    client, session = _client(
        lambda path, params: FakeResponse(pages[params["page"]], headers={"x-wp-totalpages": "3"})
    )

    result = client.list_properties(per_page=1)

    assert [record["id"] for record in result] == [1, 2, 3]
    assert [params["page"] for params in session.calls_to(PROPS)] == [1, 2, 3]


def test_list_properties_without_header_stops_on_short_page():
    client, session = _client(
        lambda path, params: FakeResponse([rest_property(id=params["page"])] if params["page"] < 3 else [])
    )

    result = client.list_properties(per_page=1)

    assert [record["id"] for record in result] == [1, 2]
    assert len(session.calls) == 3


def test_list_properties_page_limit_guard(monkeypatch):
    monkeypatch.setattr(rest_client, "MAX_PAGES", 2)
    client, _ = _client(lambda path, params: FakeResponse([rest_property()], headers={"X-WP-TotalPages": "99"}))

    with pytest.raises(AvartenRestError, match="page limit"):
        client.list_properties()


@pytest.mark.parametrize(
    "response",
    [
        FakeResponse({"code": "x"}),
        FakeResponse([rest_property(), "not-an-object"]),
        FakeResponse(status_code=500),
        FakeResponse(status_code=400, headers={}),
        FakeResponse(invalid_json=True),
        connection_error(),
    ],
)
def test_list_properties_failures_raise_readable_error(response):
    client, _ = _client(lambda path, params: response)
    with pytest.raises(AvartenRestError):
        client.list_properties()


# --------------------------------------------------------- single property

def test_get_property_by_id():
    client, session = _client(lambda path, params: FakeResponse(rest_property(id=26161)))

    record = client.get_property(post_id=26161, fields="id,slug")

    assert record["id"] == 26161
    assert session.calls == [(f"{PROPS}/26161", {"_fields": "id,slug"})]


def test_get_property_missing_id_returns_none():
    client, _ = _client(lambda path, params: FakeResponse({"code": "rest_post_invalid_id"}, status_code=404))
    assert client.get_property(post_id=999999999) is None


def test_get_property_by_slug_uses_slug_filter():
    client, session = _client(lambda path, params: FakeResponse([rest_property()]))

    record = client.get_property(slug="laya-courtyard-at-dubai-studio-city")

    assert record["slug"] == "laya-courtyard-at-dubai-studio-city"
    assert session.calls[0][1]["slug"] == "laya-courtyard-at-dubai-studio-city"
    assert session.calls[0][1]["per_page"] == 1


def test_get_property_unknown_slug_returns_none():
    client, _ = _client(lambda path, params: FakeResponse([]))
    assert client.get_property(slug="nope") is None


def test_get_property_server_error_is_not_reported_as_missing():
    client, _ = _client(lambda path, params: FakeResponse(status_code=500))
    with pytest.raises(AvartenRestError, match="HTTP 500"):
        client.get_property(post_id=1)


def test_get_property_requires_an_identifier():
    client, _ = _client(lambda path, params: FakeResponse([]))
    with pytest.raises(ValueError):
        client.get_property()


# ------------------------------------------------------------------ media

def test_get_media_is_batched_and_deduplicated():
    def handler(path, params):
        ids = [int(part) for part in params["include"].split(",")]
        return FakeResponse([media_record(media_id, f"img-{media_id}") for media_id in ids])

    client, session = _client(handler)
    ids = list(range(1, 102)) + [5, 5]  # 101 unique ids -> two requests

    media = client.get_media(ids)

    assert len(media) == 101
    calls = session.calls_to(MEDIA)
    assert len(calls) == 2
    assert calls[0]["per_page"] == 100 and calls[1]["per_page"] == 1


def test_get_media_ignores_invalid_ids_and_makes_no_request_for_none():
    client, session = _client(lambda path, params: FakeResponse([]))
    assert client.get_media([None, 0, -3, True, "7"]) == {}
    assert session.calls == []


def test_get_media_non_list_response_raises():
    client, _ = _client(lambda path, params: FakeResponse({"oops": 1}))
    with pytest.raises(AvartenRestError):
        client.get_media([1])


# ------------------------------------------------------------ PHP reader

def test_php_unserialize_reads_houzez_additional_features():
    parsed = php_unserialize(additional_features(("Down Payment", "10%"), ("Zaliczka ł", "20%")))
    assert parsed[0]["fave_additional_feature_title"] == "Down Payment"
    assert parsed[1]["fave_additional_feature_title"] == "Zaliczka ł"  # byte-length aware


@pytest.mark.parametrize(
    "value",
    [
        "a:1:{i:0;s:5:\"abc\";}",   # length mismatch
        "a:2:{i:0;i:1;}",           # missing element
        "O:8:\"stdClass\":0:{}",    # objects are refused
        "s:3:\"abc\";trailing",
        "",
        "garbage",
    ],
)
def test_php_unserialize_rejects_malformed_input(value):
    with pytest.raises(PhpSerializedError):
        php_unserialize(value)
