from fastapi.testclient import TestClient


def test_health(client):
    resp = client.get("/health")
    assert resp.status_code == 200
    assert resp.json()["stage"] == "sprint6"


def test_login_invalid_code(client):
    resp = client.post(
        "/api/auth/login",
        json={"loginType": "phone_code", "credential": "18600000000", "code": "000000"},
    )
    assert resp.status_code == 401
    assert resp.json()["code"] == 10002


def test_login_and_children_crud(client, auth_headers):
    resp = client.get("/api/children", headers=auth_headers)
    assert resp.status_code == 200
    assert resp.json()["data"]["page"]["total"] == 0

    create = client.post(
        "/api/children",
        headers={**auth_headers, "Idempotency-Key": "demo-child-1"},
        json={
            "name": "小明",
            "birthday": "2016-03-15",
            "gender": "male",
            "height": 142.5,
            "weight": 36.0,
        },
    )
    assert create.status_code == 201
    child_id = create.json()["data"]["id"]
    assert create.json()["data"]["age"] >= 9

    detail = client.get(f"/api/children/{child_id}", headers=auth_headers)
    assert detail.status_code == 200
    assert detail.json()["data"]["name"] == "小明"

    updated = client.patch(
        f"/api/children/{child_id}",
        headers=auth_headers,
        json={
            "name": "小明同学",
            "birthday": "2016-03-15",
            "gender": "male",
        },
    )
    assert updated.status_code == 200
    assert updated.json()["data"]["name"] == "小明同学"

    archived = client.delete(f"/api/children/{child_id}", headers=auth_headers)
    assert archived.status_code == 204

    missing = client.get(f"/api/children/{child_id}", headers=auth_headers)
    assert missing.status_code == 404


def test_children_requires_auth(client):
    resp = client.get("/api/children")
    assert resp.status_code == 401


def test_reports_requires_auth(client):
    resp = client.get("/api/reports/1")
    assert resp.status_code == 401
