"""INV-FIX-002 / INV-AUD-012: TripInvest offer fetching is limited to https://(www.)tripinvest.pl.

validate_tripinvest_offer_url guards the CRM import route; fetch_html validates
the URL and every redirect target before requesting it. requests.get is
replaced by a recorder, so no network is used.
"""
import pytest

import InvestmentManager.routes.foreign_offers as foreign_routes
import integrations.tripinvest.helpers as helpers
from integrations.tripinvest.helpers import UnsafeTripinvestUrl, fetch_html, validate_tripinvest_offer_url
from tests.investmentmanager.test_foreign_developments_routes import _login, foreign_db  # noqa: F401

OFFER = "https://tripinvest.pl/oferta/apartament-w-torrevieja-75156"


@pytest.mark.parametrize("url", [
    OFFER,
    "https://www.tripinvest.pl/oferta/willa-z-basenem-75001",
    "https://TRIPINVEST.pl/oferta/apartament-75156?ref=crm#galeria",
    "https://tripinvest.pl:443/oferta/apartament-75156",
    "  https://tripinvest.pl/oferta/apartament-75156  ",
])
def test_tripinvest_offer_urls_are_accepted(url):
    assert validate_tripinvest_offer_url(url) == url.strip()


@pytest.mark.parametrize("url", [
    None, "", "tripinvest.pl/oferta/x",
    "http://tripinvest.pl/oferta/apartament-75156",           # https only
    "https://evil.example/?next=tripinvest.pl/oferta/x",      # old substring check accepted this
    "https://evil.example/tripinvest.pl/oferta/x",
    "https://tripinvest.pl.evil.example/oferta/x",
    "https://evil.tripinvest.pl/oferta/x",
    "https://tripinvest.pl@evil.example/oferta/x",
    "https://user:pass@tripinvest.pl/oferta/x",
    "https://tripinvest.pl:8080/oferta/x",
    "https://localhost/oferta/x",
    "https://127.0.0.1/oferta/x",
    "https://169.254.169.254/latest/meta-data/?tripinvest.pl/oferta/",
    "https://[::1]/oferta/x",
    "https://tripinvest.pl/",
    "https://tripinvest.pl/oferta/",
    "https://tripinvest.pl/hiszpania/costa-blanca",
    "file:///etc/passwd",
    "javascript:alert(1)//tripinvest.pl/oferta/x",
])
def test_other_urls_are_rejected(url):
    with pytest.raises(UnsafeTripinvestUrl):
        validate_tripinvest_offer_url(url)


class FakeResponse:
    def __init__(self, status=200, location=None, text="<html><h1>Oferta</h1></html>"):
        self.status_code = status
        self.headers = {"Location": location} if location else {}
        self.text = text

    @property
    def is_redirect(self):
        return self.status_code in (301, 302, 303, 307, 308) and "Location" in self.headers

    def raise_for_status(self):
        if self.status_code >= 400:
            raise RuntimeError(self.status_code)


@pytest.fixture()
def http(monkeypatch):
    calls, responses = [], {}

    def fake_get(url, **kwargs):
        calls.append((url, kwargs.get("allow_redirects")))
        return responses.get(url, FakeResponse())

    monkeypatch.setattr(helpers.requests, "get", fake_get)
    return calls, responses


def test_fetch_html_requests_a_valid_offer_without_auto_redirects(http):
    calls, _ = http
    soup = fetch_html(OFFER)
    assert soup.h1.get_text() == "Oferta"
    assert calls == [(OFFER, False)]


def test_redirect_inside_tripinvest_is_followed(http):
    calls, responses = http
    responses[OFFER] = FakeResponse(301, "/oferta/apartament-w-torrevieja-nowy-slug-75156")
    fetch_html(OFFER)
    assert [url for url, _ in calls] == [OFFER, "https://tripinvest.pl/oferta/apartament-w-torrevieja-nowy-slug-75156"]


@pytest.mark.parametrize("location", [
    "http://169.254.169.254/latest/meta-data/",
    "https://127.0.0.1/admin",
    "http://tripinvest.pl/oferta/x",
    "https://tripinvest.pl.evil.example/oferta/x",
    "//evil.example/x",
])
def test_redirect_outside_tripinvest_is_never_requested(http, location):
    calls, responses = http
    responses[OFFER] = FakeResponse(302, location)
    with pytest.raises(UnsafeTripinvestUrl):
        fetch_html(OFFER)
    assert [url for url, _ in calls] == [OFFER]


def test_redirect_loop_is_bounded(http):
    calls, responses = http
    responses[OFFER] = FakeResponse(302, OFFER)
    with pytest.raises(UnsafeTripinvestUrl):
        fetch_html(OFFER)
    assert len(calls) == helpers.MAX_TRIPINVEST_REDIRECTS + 1


def test_invalid_url_is_rejected_before_any_request(http):
    calls, _ = http
    with pytest.raises(UnsafeTripinvestUrl):
        fetch_html("http://127.0.0.1:8080/internal?next=tripinvest.pl/oferta/x")
    assert calls == []


# ---------------------------------------------------------------------------
# CRM import route
# ---------------------------------------------------------------------------


@pytest.fixture()
def admin(client, foreign_db, monkeypatch):
    _login(client)
    imported = []
    monkeypatch.setattr(foreign_routes, "upsert_foreign_offer_from_tripinvest",
                        lambda url: imported.append(url) or {"foreign_offer_id": 1})
    return client, imported


def test_import_route_accepts_tripinvest_offer(admin):
    client, imported = admin
    response = client.post("/crm/foreign-offers/import", json={"url": f"  {OFFER}  "})
    assert response.status_code == 200
    assert imported == [OFFER]


@pytest.mark.parametrize("url", [
    "http://127.0.0.1:8080/internal?next=tripinvest.pl/oferta/x",
    "https://evil.example/tripinvest.pl/oferta/x",
    "http://tripinvest.pl/oferta/apartament-75156",
])
def test_import_route_rejects_non_tripinvest_urls(admin, url):
    client, imported = admin
    response = client.post("/crm/foreign-offers/import", json={"url": url})
    assert response.status_code == 400
    assert response.get_json() == {"error": "Na ten moment obsługiwane są tylko linki ofert Tripinvest."}
    assert imported == []
