# pyright: reportCallIssue=false

from __future__ import annotations
from behave import then, when

from KVSTest.testdata.kvs_test_data import KVSTestData

@when("add user to kvs place")  # pyright: ignore[reportGeneralTypeIssues]
def step_add_user_to_place(context) -> None:
    td = KVSTestData.from_behave_context(context)
    place_id = getattr(context, "kvs_place_id", None) or td.place_id
    account_id = getattr(context, "kvs_account_id", None) or td.account_id
    assert isinstance(place_id, str) and place_id, "Нет kvs_place_id (place не создан)."
    assert isinstance(account_id, str) and account_id, "Нет kvs_account_id (user не создан)."

    resp = td.add_user_to_place(account_id=account_id, place_id=place_id)
    context.kvs_add_user_to_place_response = resp
    
@then("addUserToPlace response is valid")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_add_user_to_place_response(context) -> None:
    td = KVSTestData.from_behave_context(context)
    place_id = getattr(context, "kvs_place_id", None) or td.place_id
    assert isinstance(place_id, str) and place_id, "Нет kvs_place_id."

    resp = getattr(context, "kvs_add_user_to_place_response", None)
    assert isinstance(resp, dict), f"Ответ GraphQL не dict: {resp!r}"
    assert "data" in resp, f"В ответе нет data: {resp!r}"
    data = resp.get("data", {}) if isinstance(resp.get("data", {}), dict) else {}
    payload = None
    for key in ("addUserToPlace", "addMemberToPlace", "addUserToPlaceWithRole"):
        if key in data:
            payload = data.get(key)
            break
    assert isinstance(payload, dict), f"data.add*ToPlace не объект (ожидали JSONObject c полями place_id/member_id). data={data!r}"
    assert payload.get("place_id") == place_id, f"place_id не совпал: {payload!r}"
    member_id = payload.get("member_id")
    assert isinstance(member_id, str) and member_id, f"member_id пустой/не строка: {payload!r}"
    context.kvs_member_id = member_id


@then("added member is present in place members results")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_member_present(context) -> None:
    member_id = getattr(context, "kvs_member_id", None)
    assert isinstance(member_id, str) and member_id, "Нет kvs_member_id (невалидный addUserToPlace ответ)."

    resp = getattr(context, "kvs_place_members_response", None)
    assert isinstance(resp, dict), f"Ответ GraphQL не dict: {resp!r}"
    results = resp.get("data", {}).get("place", {}).get("results", [])
    assert isinstance(results, list) and results, f"data.place.results пустой/не list: {results!r}"
    members = results[0].get("members") if isinstance(results[0], dict) else None
    assert isinstance(members, list), f"members не list: {members!r}"
    ids = [m.get("id") for m in members if isinstance(m, dict)]
    assert member_id in ids, f"Не нашли member_id={member_id!r} в members ids={ids!r}"

