# backend/tests/test_meeting_materialize.py
# phase-16+: 일정 시드 제거 → 회의/액션을 테스트가 직접 생성.
from app.models import Task
from tests._factories import make_cal_event, make_meeting, make_meeting_action


def _setup_e3(s):
    make_cal_event(s, id="e3", cal="team", title="팀 스탠드업")
    make_meeting(s, event_id="e3", phase="done")
    make_meeting_action(s, id="ma1", meeting_id="e3", idx=2, text="매출 데이터 전달", who="현우")


def test_materialize_one_creates_task(client, session):
    s, _ = session
    _setup_e3(s)
    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 '현우' → hyunwoo
    assert data["task"]["project_id"] == "biz"  # team/work/meeting → biz
    assert data["all_added"] is True  # 유일한 미처리 액션이었음
    assert s.get(Task, data["task"]["id"]) is not None


def test_materialize_idempotent(client, session):
    s, _ = session
    _setup_e3(s)
    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, session):
    s, _ = session
    make_cal_event(s, id="e4", cal="work", title="디자인 리뷰")
    make_meeting(s, event_id="e4", phase="live")
    make_meeting_action(s, id="ea1", meeting_id="e4", idx=0,
                        text="온보딩 3번 화면 CTA 수정안 반영", who="나")
    arr = client.post("/api/calendar/meetings/e4/actions/materialize-all").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, session):
    s, _ = session
    _setup_e3(s)
    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)
