# backend/tests/test_meeting_materialize.py
from app.models import Task


def test_materialize_one_creates_task(client, session):
    s, _ = session
    # e3 idx=2 "매출 데이터 전달" (현우, added=False)
    r = client.post("/api/calendar/meetings/e3/actions/2/materialize")
    assert r.status_code == 200
    data = r.json()
    assert data["action"]["added"] is True
    assert data["task"]["title"] == "매출 데이터 전달"
    assert data["task"]["assignee_id"] == "hyunwoo"  # who 나매핑
    assert data["task"]["project_id"] == "biz"  # team/work/meeting → biz
    assert data["all_added"] is True  # e3 의 마지막 미처리 액션이었음
    tid = data["task"]["id"]
    assert s.get(Task, tid) is not None  # federation: 작업 페이지에 등장


def test_materialize_idempotent(client):
    r1 = client.post("/api/calendar/meetings/e3/actions/2/materialize")
    t1 = r1.json()["task"]["id"]
    r2 = client.post("/api/calendar/meetings/e3/actions/2/materialize")
    assert r2.json()["task"]["id"] == t1  # 중복 생성 없음


def test_materialize_all(client):
    # e4(live) 액션 1건 모두
    r = client.post("/api/calendar/meetings/e4/actions/materialize-all")
    arr = r.json()
    assert len(arr) == 1
    assert arr[0]["task"]["title"] == "온보딩 3번 화면 CTA 수정안 반영"
    assert arr[0]["all_added"] is True


def test_materialize_action_appears_in_tasks(client):
    client.post("/api/calendar/meetings/e3/actions/2/materialize")
    tasks = client.get("/api/tasks?area=work").json()

    def has(nodes):
        for n in nodes:
            if n["title"] == "매출 데이터 전달":
                return True
            if has(n.get("children", [])):
                return True
        return False

    assert has(tasks)
