def test_template_crud_packs_and_unpacks_mapping_rules(client):
    payload = {
        "name": "Template",
        "color": "#06b6d4",
        "z_index": 0,
        "classes": [{"id": "c1", "name": "胆囊", "color": "#ff0000", "zIndex": 10}],
        "rules": [{"id": "r1", "name": "rule"}],
    }

    created = client.post("/api/templates", json=payload)
    assert created.status_code == 201
    template_id = created.json()["id"]
    assert created.json()["classes"][0]["name"] == "胆囊"
    assert created.json()["rules"][0]["id"] == "r1"

    listing = client.get("/api/templates")
    assert listing.status_code == 200
    assert listing.json()[0]["classes"][0]["name"] == "胆囊"

    detail = client.get(f"/api/templates/{template_id}")
    assert detail.status_code == 200
    assert detail.json()["name"] == "Template"

    updated = client.patch(f"/api/templates/{template_id}", json={
        "classes": [{"id": "c2", "name": "肝脏", "color": "#00ff00", "zIndex": 20}],
        "rules": [],
    })
    assert updated.status_code == 200
    assert updated.json()["classes"][0]["name"] == "肝脏"

    deleted = client.delete(f"/api/templates/{template_id}")
    assert deleted.status_code == 204
    assert client.get(f"/api/templates/{template_id}").status_code == 404


def test_template_404s(client):
    assert client.get("/api/templates/999").status_code == 404
    assert client.patch("/api/templates/999", json={"name": "x"}).status_code == 404
    assert client.delete("/api/templates/999").status_code == 404
