# backend/tests/test_api_tasks.py — 작업 API (phase-16+: 작업 시드 제거 → 테스트가 직접 생성)
from tests._factories import make_comment, make_task


def test_tasks_nested_and_filter(client, session):
    s, _ = session
    make_task(s, id="w1", project_id="biz-report", title="부모 작업")
    make_task(s, id="w1a", project_id="biz-report", parent_id="w1", title="자식 작업")
    make_comment(s, id="cm1", task_id="w1")
    make_comment(s, id="cm2", task_id="w1")
    make_task(s, id="l1", project_id="me", title="라이프 작업")

    work = client.get("/api/tasks?area=work").json()
    w1 = next(t for t in work if t["id"] == "w1")
    assert w1["children"], "w1 has subtasks"
    assert len(w1["comments"]) == 2
    life = client.get("/api/tasks?area=life").json()
    assert {t["id"] for t in life} >= {"l1"}


def test_task_status_move(client, session):
    s, _ = session
    make_task(s, id="t1", project_id="biz-report")
    r = client.patch("/api/tasks/t1", json={"status": "review"}).json()
    assert r["status"] == "review"


def test_task_comment(client, session):
    s, _ = session
    make_task(s, id="t1", project_id="biz-report")
    c = client.post(
        "/api/tasks/t1/comments", json={"person_id": "minseo", "text": "확인했습니다"}
    ).json()
    assert c["text"] == "확인했습니다"


def test_task_filter_project_subtree(client, session):
    s, _ = session
    make_task(s, id="a1", project_id="biz-report")
    make_task(s, id="a2", project_id="biz-okr")
    r = client.get("/api/tasks?project_id=biz").json()
    ids = {t["id"] for t in r}
    assert "a1" in ids and "a2" in ids  # biz(+하위) 서브트리


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, session):
    s, _ = session
    make_task(s, id="p1", project_id="biz-report", title="부모")
    body = {"title": "새 하위", "project_id": "biz-report", "parent_id": "p1", "status": "todo"}
    child = client.post("/api/tasks", json=body).json()
    parent = client.get("/api/tasks/p1").json()
    assert any(c["id"] == child["id"] for c in parent["children"])


def test_patch_status_persists(client, session):
    s, _ = session
    make_task(s, id="t1", project_id="me")
    client.patch("/api/tasks/t1", json={"status": "done"})
    assert client.get("/api/tasks/t1").json()["status"] == "done"


def test_cannot_parent_to_self_or_descendant(client, session):
    s, _ = session
    make_task(s, id="t1", project_id="biz-report")
    # 자기 자신을 부모로 → 400 (순환 방지)
    assert client.patch("/api/tasks/t1", json={"parent_id": "t1"}).status_code == 400
