# backend/tests/test_approvals_service.py — 큐 분기 / 상태 전이
def test_derive_queue_mixed(client):
    q = client.get("/api/approvals").json()
    assert q["autonomy"] == "mixed"
    # high 3(phase-7) + ap-er1(phase-14 심부름 게이트) = 4 대기, low 3 자동
    assert len(q["pending"]) == 4 and len(q["done"]) == 3
    assert {a["risk"] for a in q["pending"]} == {"high"}
    assert {a["risk"] for a in q["done"]} == {"low"}


def test_autonomy_approval_first_all_pending(client):
    client.patch("/api/approvals/autonomy", json={"level": "approval_first"})
    q = client.get("/api/approvals").json()
    assert len(q["pending"]) == 7 and len(q["done"]) == 0  # +ap-er1(phase-14)
    assert q["badges_appr"] == 7


def test_autonomy_full_auto_empty_queue(client):
    client.patch("/api/approvals/autonomy", json={"level": "full_auto"})
    q = client.get("/api/approvals").json()
    assert len(q["pending"]) == 0 and len(q["done"]) == 7  # 빈 큐(+ap-er1) → appr-empty


def test_invalid_autonomy_422(client):
    r = client.patch("/api/approvals/autonomy", json={"level": "bogus"})
    assert r.status_code == 422


def test_approve_and_undo_cycle(client):
    a4 = client.post("/api/approvals/a4/approve").json()
    assert a4["status"] == "executed"
    back = client.post("/api/approvals/a4/undo").json()
    assert back["status"] == "undone"
    q = client.get("/api/approvals").json()  # undone → 다시 pending 으로 표시
    assert any(a["id"] == "a4" for a in q["pending"])


def test_approve_all(client):
    n = client.post("/api/approvals/approve-all").json()["approved"]
    assert n == 4  # mixed 의 high 3건 + 심부름 게이트 1건(phase-14)
    q = client.get("/api/approvals").json()
    assert len(q["pending"]) == 0


def test_saved_and_count_constants(client):
    q = client.get("/api/approvals").json()
    assert q["saved_today"] == "47분" and q["auto_count_night"] == 7
    assert len(q["log"]) == 4


def test_approve_404(client):
    assert client.post("/api/approvals/nope/approve").status_code == 404


def test_execute_equals_approve(client):
    a5 = client.post("/api/approvals/a5/execute").json()
    assert a5["status"] == "executed"
