"""AvartenConnector.fetch_full_catalog(): the bulk canonical catalog used by source sync.

Offline (FakeSite); proves the request budget and that REST failures are not masked.
"""
import pytest

from integrations.avarten.rest_client import AvartenRestError, MEDIA_ENDPOINT, PROPERTIES_ENDPOINT
from integrations.avarten.connector import AvartenConnector
from tests.avarten.avarten_rest_fixtures import BASE, connection_error, media_record, rest_property
from tests.avarten.test_avarten_rest_connector import FakeSite


def _site(**kwargs):
    first = rest_property(id=1, slug="one", link=f"{BASE}/property/one/", title={"rendered": "One"},
                          meta={"fave_property_images": ["11", "12"]})
    cheap = rest_property(id=2, slug="two", link=f"{BASE}/property/two/", title={"rendered": "Two"},
                          featured_media=22, meta={"fave_property_price": ["300000"], "fave_property_images": []})
    no_media = rest_property(id=3, slug="three", link=f"{BASE}/property/three/", title={"rendered": "Three"},
                             featured_media=0, meta={"fave_property_images": ["99"]})   # 99 is not in the library
    media = [media_record(11, "One-a"), media_record(12, "One-b"), media_record(22, "Two-cover")]
    return FakeSite([first, cheap, no_media], media, **kwargs)


def test_returns_every_property_as_a_canonical_offer_with_description_and_gallery():
    site = _site()

    offers = site.connector().fetch_full_catalog()

    assert [o["source"]["external_id"] for o in offers] == ["1", "2", "3"]
    assert offers[0]["listing"]["description_text"].startswith("Laya Courtyard at Dubai Studio City")
    assert offers[0]["media"]["gallery"] == [
        f"{BASE}/wp-content/uploads/2025/04/One-a-1170x785.jpg",
        f"{BASE}/wp-content/uploads/2025/04/One-b-1170x785.jpg",
    ]
    assert offers[1]["media"]["gallery"] == [f"{BASE}/wp-content/uploads/2025/04/Two-cover-1170x785.jpg"]  # featured fallback
    assert offers[2]["media"]["gallery"] == []  # media that no longer exists is skipped, not guessed
    assert all(o["raw"]["payload"]["data_source"] == "wp_rest" for o in offers)


def test_uses_one_list_request_and_one_media_request_for_the_whole_catalog():
    site = _site()

    site.connector().fetch_full_catalog()

    assert len(site.session.calls_to(PROPERTIES_ENDPOINT)) == 1
    assert len(site.session.calls_to(MEDIA_ENDPOINT)) == 1
    assert len(site.session.calls) == 2
    assert "content" in site.session.calls_to(PROPERTIES_ENDPOINT)[0]["_fields"].split(",")


def test_the_public_catalog_price_range_does_not_apply():
    offers = _site().connector().fetch_full_catalog()
    assert 300000 in [o["pricing"]["amount"] for o in offers]


@pytest.mark.parametrize(
    "site_kwargs",
    [{"list_error": connection_error()}, {"list_status": 503}, {"media_error": connection_error()}],
)
def test_rest_failures_raise_and_never_fall_back_to_the_html_pages(monkeypatch, site_kwargs):
    def html_must_not_run(self, *args, **kwargs):
        raise AssertionError("HTML fallback used for the sync catalog")

    monkeypatch.setattr(AvartenConnector, "_fetch_catalog_html", html_must_not_run)
    monkeypatch.setattr(AvartenConnector, "_fetch_offer_html", html_must_not_run)

    with pytest.raises(AvartenRestError):
        _site(**site_kwargs).connector().fetch_full_catalog()


def test_an_empty_catalog_is_a_failure_not_an_empty_result():
    with pytest.raises(AvartenRestError, match="no properties"):
        FakeSite([]).connector().fetch_full_catalog()


def test_the_public_paginated_catalog_is_unchanged():
    items, meta = _site().connector().fetch_catalog({}, 1, 24)   # price range still applies there
    assert [i["offer"]["id"] for i in items] == [1, 3]   # the 300 000 offer (id 2) is filtered out there
    assert meta["total_pages"] == 1
