def test_tasks_nested_and_filter(client):
    work = client.get("/api/tasks?area=work").json()
    k1 = next(t for t in work if t["id"] == "k1")
    assert k1["children"], "k1 has subtasks"
    assert len(k1["comments"]) == 2
    life = client.get("/api/tasks?area=life").json()
    assert {t["id"] for t in life} >= {"k4", "k20", "k21"}


def test_task_status_move(client):
    r = client.patch("/api/tasks/k1", json={"status": "review"}).json()
    assert r["status"] == "review"


def test_task_comment(client):
    c = client.post(
        "/api/tasks/k1/comments", json={"person_id": "minseo", "text": "확인했습니다"}
    ).json()
    assert c["text"] == "확인했습니다"


def test_task_filter_project_subtree(client):
    # biz 프로젝트(+하위)의 작업: k1(biz-report), k6(biz-okr) 등 포함
    r = client.get("/api/tasks?project_id=biz").json()
    ids = {t["id"] for t in r}
    assert "k1" in ids and "k6" in ids


def test_task_create_and_delete(client):
    created = client.post("/api/tasks", json={"title": "신규 작업", "project_id": "me"}).json()
    tid = created["id"]
    assert created["status"] == "todo"
    assert client.delete(f"/api/tasks/{tid}").json()["deleted"] == tid


def test_create_subtask_parent(client):
    body = {"title": "새 하위", "project_id": "biz-report", "parent_id": "k1", "status": "todo"}
    child = client.post("/api/tasks", json=body).json()
    parent = client.get("/api/tasks/k1").json()
    assert any(c["id"] == child["id"] for c in parent["children"])


def test_patch_status_persists(client):
    client.patch("/api/tasks/k4", json={"status": "done"})
    assert client.get("/api/tasks/k4").json()["status"] == "done"


def test_cannot_parent_to_self_or_descendant(client):
    # 자기 자신을 부모로 → 400 (순환 방지)
    assert client.patch("/api/tasks/k1", json={"parent_id": "k1"}).status_code == 400
