from fastapi.testclient import TestClient

def _client():
    from app.main import app
    return TestClient(app)

def test_criteria_get_default_and_put():
    c = _client()
    assert c.get("/api/realestate/listings/criteria").json()["max_deposit"] == 32000
    c.put("/api/realestate/listings/criteria", json={"max_deposit": 30000})
    assert c.get("/api/realestate/listings/criteria").json()["max_deposit"] == 30000

def test_budget_endpoint():
    r = _client().post("/api/realestate/budget", json={"equity": 30000, "annual_income": 8000,
                       "is_homeless": True, "is_householder": True, "is_first_home": False, "target_dong": "상도동"})
    b = r.json()
    assert "jeonse" in b and "purchase" in b and "region" in b
    assert b["purchase"]["max_price"] == b["purchase"]["loan_cap"] + 30000

def test_safety_check_rent():
    from app import db
    for v in (40000, 42000, 44000):
        db.upsert_market_deal({"house_type": "아파트", "dong_code": "11590", "dong": "신대방동",
                               "complex_name": "OO", "area": 42.0, "deal_type": "전세",
                               "deposit": v, "sale_amount": None, "deal_ym": "202606", "floor": "5"})
    r = _client().post("/api/realestate/safety-check",
                       json={"complex_name": "OO", "area": 42.0, "deal_type": "전세",
                             "amount": 28000, "dong_code": "11590"})
    j = r.json()
    assert j["tier"] == "안전" and "disclaimer" in j

def test_listings_collect_status():
    assert _client().get("/api/realestate/listings/collect/status").status_code == 200
