"""SPAIN-REFRESH-GUARD-1: legacy refresh endpoints are TripInvest-only."""
import sqlite3

import pytest

import InvestmentManager.routes.foreign_offers as foreign_offer_routes
from tests.investmentmanager.test_foreign_developments_routes import _login, foreign_db  # noqa: F401


def _connect(db_path):
    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    return conn


def _insert_offer(conn, offer_id, source_platform, source_url, *, active=True):
    conn.execute(
        """
        INSERT INTO foreign_offers (
            id, source_platform, source_url, offer_title, is_active
        )
        VALUES (?, ?, ?, ?, ?)
        """,
        (offer_id, source_platform, source_url, f"Offer {offer_id}", 1 if active else 0),
    )


@pytest.fixture()
def refresh_db(foreign_db):
    conn = _connect(foreign_db)
    try:
        conn.execute("UPDATE foreign_offers SET is_active = 0 WHERE id = 5")
        _insert_offer(conn, 10, "avarten", "https://avartenproperties.com/property/laya/", active=True)
        _insert_offer(
            conn,
            11,
            "cyprus_constructions",
            "https://www.cyprusconstructions.com/pl/Aloha_Homes#unit-type=x",
            active=True,
        )
        _insert_offer(conn, 12, "tripinvest", "https://tripinvest.pl/oferta/inactive-12", active=False)
        conn.commit()
    finally:
        conn.close()
    return foreign_db


@pytest.fixture()
def admin(client, refresh_db):
    _login(client)
    return client


def _spy_tripinvest_importer(monkeypatch):
    calls = []

    def fake(source_url):
        calls.append(source_url)
        return {"source_url": source_url, "source_platform": "tripinvest"}

    monkeypatch.setattr(foreign_offer_routes, "upsert_foreign_offer_from_tripinvest", fake)
    return calls


def test_refresh_all_processes_only_active_tripinvest_rows(admin, monkeypatch):
    calls = _spy_tripinvest_importer(monkeypatch)

    response = admin.post("/crm/foreign-offers/refresh-all")

    assert response.status_code == 200
    assert calls == ["https://tripinvest.pl/oferta/offer-1"]
    assert response.get_json() == {
        "ok": True,
        "results": [{"source_url": "https://tripinvest.pl/oferta/offer-1", "source_platform": "tripinvest"}],
        "errors": [],
        "refreshed_count": 1,
        "error_count": 0,
        "total_count": 1,
    }


def test_single_refresh_still_processes_tripinvest_row(admin, monkeypatch):
    calls = _spy_tripinvest_importer(monkeypatch)

    response = admin.post("/crm/foreign-offers/refresh/1")

    assert response.status_code == 200
    assert calls == ["https://tripinvest.pl/oferta/offer-1"]
    assert response.get_json()["item"]["source_platform"] == "tripinvest"


@pytest.mark.parametrize("offer_id,source", [(10, "avarten"), (11, "cyprus_constructions")])
def test_single_refresh_rejects_non_tripinvest_rows(admin, monkeypatch, offer_id, source):
    calls = _spy_tripinvest_importer(monkeypatch)

    response = admin.post(f"/crm/foreign-offers/refresh/{offer_id}")

    assert response.status_code == 400
    assert "TripInvest" in response.get_json()["error"]
    assert calls == []


def test_import_endpoint_keeps_existing_tripinvest_url_guard(admin, monkeypatch):
    calls = _spy_tripinvest_importer(monkeypatch)

    rejected = admin.post("/crm/foreign-offers/import", json={"url": "https://avartenproperties.com/property/laya/"})
    accepted = admin.post("/crm/foreign-offers/import", json={"url": "https://tripinvest.pl/oferta/offer-1"})

    assert rejected.status_code == 400
    assert "Tripinvest" in rejected.get_json()["error"]
    assert accepted.status_code == 200
    assert calls == ["https://tripinvest.pl/oferta/offer-1"]
