"""app (FastAPI) 黑盒测试，走 TestClient + 真 sqlite（tmp）。"""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    from xiangqin.app import app

    return TestClient(app)


def test_health(client):
    r = client.get("/health")
    assert r.status_code == 200
    assert r.json()["status"] == "ok"


def test_register_verify_flow(client):
    r = client.post("/auth/register", json={"phone": "13800001234"})
    assert r.status_code == 200
    req_id = r.json()["request_id"]
    assert req_id

    v = client.post("/auth/verify", json={"request_id": req_id, "code": "123456"})
    assert v.status_code == 200
    token = v.json()["session_token"]
    assert token

    me = client.get("/auth/me", headers={"Authorization": f"Bearer {token}"})
    assert me.status_code == 200


def test_me_unauthenticated(client):
    r = client.get("/auth/me")
    assert r.status_code == 401


def test_verify_wrong_code_returns_400(client):
    r = client.post("/auth/register", json={"phone": "13800005555"})
    req_id = r.json()["request_id"]
    v = client.post("/auth/verify", json={"request_id": req_id, "code": "000000"})
    assert v.status_code == 400


def _login(client, phone="13800009999") -> str:
    r = client.post("/auth/register", json={"phone": phone})
    req_id = r.json()["request_id"]
    v = client.post("/auth/verify", json={"request_id": req_id, "code": "123456"})
    return v.json()["session_token"]


def test_profile_get_empty(client):
    token = _login(client)
    r = client.get("/profile/me", headers={"Authorization": f"Bearer {token}"})
    assert r.status_code == 200


def test_profile_put_and_read(client):
    token = _login(client, "13800001001")
    headers = {"Authorization": f"Bearer {token}"}
    r = client.put(
        "/profile/me",
        headers=headers,
        json={"gender": "f", "age": 28, "city": "hangzhou", "tags": ["a"], "bio": "hi"},
    )
    assert r.status_code == 200
    assert r.json()["age"] == 28

    r = client.get("/profile/me", headers=headers)
    assert r.json()["gender"] == "f"


def test_query_requires_auth(client):
    r = client.post("/query", json={"where": "gender=f"})
    assert r.status_code == 401


def test_query_basic(client):
    # 建一个 f 用户
    t1 = _login(client, "13800002001")
    client.put(
        "/profile/me",
        headers={"Authorization": f"Bearer {t1}"},
        json={"gender": "f", "age": 25, "city": "hangzhou", "tags": [], "bio": ""},
    )
    # 另一个用户查
    t2 = _login(client, "13800002002")
    r = client.post(
        "/query",
        headers={"Authorization": f"Bearer {t2}"},
        json={"where": "gender=f AND city=hangzhou", "limit": 10},
    )
    assert r.status_code == 200
    assert "results" in r.json()


def test_logout(client):
    token = _login(client, "13800004001")
    r = client.post("/auth/logout", headers={"Authorization": f"Bearer {token}"})
    assert r.status_code == 200
