# pyright: reportCallIssue=false

from __future__ import annotations

from behave import then, when

from Pass_request.testdata.pass_request_test_data import PassRequestTestData


@when("prepare place, entrance, service and user for pass")  # pyright: ignore[reportGeneralTypeIssues]
def step_prepare_pass_prereqs(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    td.ensure_place()
    # Entrance в новом API создаётся через createEntrance и требует devices.
    # Не делаем его обязательным для passRequests сценариев.
    td.ensure_service()
    td.ensure_user_attached_to_place()


@when("create pass for prepared place")  # pyright: ignore[reportGeneralTypeIssues]
def step_create_pass(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    context.pass_id = td.create_pass()


@when("query passRequests by created pass_id")  # pyright: ignore[reportGeneralTypeIssues]
def step_query_pass_requests(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    context.pass_requests_response = td.wait_for_pass_request()


@then("passRequests response contains created pass")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_pass_requests(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    resp = getattr(context, "pass_requests_response", None)
    assert isinstance(resp, dict) and "data" in resp, f"Некорректный passRequests ответ: {resp!r}"

    payload = resp.get("data", {}).get("passRequests")
    assert isinstance(payload, dict), f"data.passRequests не объект: {payload!r}"
    results = payload.get("results")
    assert isinstance(results, list), f"data.passRequests.results не list: {results!r}"

    pass_id = td.pass_id
    assert isinstance(pass_id, str) and pass_id, "Нет pass_id в testdata."
    matched = None
    for r in results:
        if isinstance(r, dict) and r.get("pass_id") == pass_id:
            matched = r
            break
    assert isinstance(matched, dict), f"В results нет записи с pass_id={pass_id!r}. results={results!r}"

    expected_place_id = td.expected_pass_request_place_id
    assert isinstance(expected_place_id, str) and expected_place_id, "Нет expected_pass_request_place_id в testdata."
    assert matched.get("place_id") == expected_place_id, (
        "PassRequest должен создаваться в родительском месте от места, где создан pass. "
        f"Ожидали place_id={expected_place_id!r}, получили: {matched.get('place_id')!r}"
    )


@when("prepare place with owner and trusted worker for members query")  # pyright: ignore[reportGeneralTypeIssues]
def step_prepare_place_with_owner_and_worker(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    td.prepare_members_trusted_flow()


@when("query members for prepared place")  # pyright: ignore[reportGeneralTypeIssues]
def step_query_members_for_place(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    context.members_response = td.query_members_by_place()


@then("members response contains trusted worker with accepted status")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_trusted_worker_member(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    resp = getattr(context, "members_response", None)
    assert isinstance(resp, dict), f"Некорректный members ответ: {resp!r}"
    td.assert_worker_member_trusted_and_accepted(resp)


@when("prepare four places and worker for setUserPlaces flow")  # pyright: ignore[reportGeneralTypeIssues]
def step_prepare_set_user_places_flow(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    td.prepare_set_user_places_flow()


@when("apply setUserPlaces for worker to first three places with trusted privilege")  # pyright: ignore[reportGeneralTypeIssues]
def step_apply_set_user_places(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    context.set_user_places_response = td.apply_set_user_places_for_worker()


@when("query places by worker member filter")  # pyright: ignore[reportGeneralTypeIssues]
def step_query_places_for_worker(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    context.worker_places_response = td.query_places_for_worker_member_filter()


@then("worker is in first three places with accepted trusted and absent in fourth place")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_set_user_places_result(context) -> None:
    td = PassRequestTestData.from_behave_context(context)
    resp = getattr(context, "worker_places_response", None)
    assert isinstance(resp, dict), f"Некорректный place(filters.member_ids) ответ: {resp!r}"
    td.assert_set_user_places_result(resp)

