# pyright: reportCallIssue=false

from __future__ import annotations

from behave import then, when

from KVSTest.testdata.subscription_test_data import SubscriptionTestData


@when("create service for kvs subscription")  # pyright: ignore[reportGeneralTypeIssues]
def step_create_service(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    context.kvs_service_id = td.ensure_service()


@when("create plan for kvs subscription")  # pyright: ignore[reportGeneralTypeIssues]
def step_create_plan(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    context.kvs_plan_id = td.ensure_plan()


@when("create subscription for kvs")  # pyright: ignore[reportGeneralTypeIssues]
def step_create_subscription(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    context.kvs_subscription_id = td.create_subscription()


@then("subscription response is valid")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_subscription_valid(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    sub_id = getattr(context, "kvs_subscription_id", None) or td.subscription_id
    assert isinstance(sub_id, str) and sub_id, "Нет subscription_id."
    # create_subscription already asserts response shape; here we validate cached ids coherence
    assert td.subscription_id == sub_id
    assert isinstance(td.plan_id, str) and td.plan_id, "Нет plan_id."
    assert isinstance(td.service_id, str) and td.service_id, "Нет service_id."


@when("query pending invoices for subscription place")  # pyright: ignore[reportGeneralTypeIssues]
def step_query_invoices(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    context.kvs_invoices_response = td.query_invoices()


@then("invoices response is valid and references subscription")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_invoices(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    sub_id = td.subscription_id
    assert isinstance(sub_id, str) and sub_id, "Нет subscription_id."

    resp = getattr(context, "kvs_invoices_response", None)
    assert isinstance(resp, dict) and "data" in resp, f"Некорректный invoices ответ: {resp!r}"
    invoices = resp.get("data", {}).get("invoices")
    assert isinstance(invoices, list), f"data.invoices не list: {invoices!r}"
    # допускаем, что инвойсы могут создаваться асинхронно — но если они пришли, должны быть валидной формы
    for inv in invoices:
        assert isinstance(inv, dict), f"invoice элемент не dict: {inv!r}"
        assert isinstance(inv.get("id"), str) and inv.get("id"), f"invoice.id пустой: {inv!r}"
        assert inv.get("status") in {"pending", "PENDING", "Pending"}, f"invoice.status неожиданный: {inv!r}"
    # Если стенд возвращает subscriptions — проверим, что где-то упоминается наша подписка
    referenced = False
    for inv in invoices:
        subs = inv.get("subscriptions")
        if isinstance(subs, list) and sub_id in subs:
            referenced = True
            break
        if isinstance(subs, str) and sub_id in subs:
            referenced = True
            break
    assert referenced or invoices == [], (
        "Invoices вернулись, но не содержат ссылку на созданную подписку. "
        "Если генерация invoice асинхронная — можно добавить ожидание/ретраи."
    )


@when("delete created subscription")  # pyright: ignore[reportGeneralTypeIssues]
def step_delete_subscription(context) -> None:
    td = SubscriptionTestData.from_behave_context(context)
    context.kvs_delete_subscription_response = td.delete_subscription_now()


@then("delete subscription response is successful")  # pyright: ignore[reportGeneralTypeIssues]
def step_assert_delete_subscription(context) -> None:
    resp = getattr(context, "kvs_delete_subscription_response", None)
    assert isinstance(resp, dict) and "data" in resp, f"Некорректный deleteSubscription ответ: {resp!r}"
    value = resp.get("data", {}).get("deleteSubscription")
    assert value in (True, "true", "True", 1, "1", None) or isinstance(value, dict), f"deleteSubscription вернул неожиданное: {value!r}"

