from __future__ import annotations

import pytest

from .helpers import ReleaseApiClient, flatten_route_paths


@pytest.mark.release
def test_g1_admin_auth_and_rbac_context(admin_client: ReleaseApiClient) -> None:
    me_response = admin_client.get("/api/auth/me")
    me = ReleaseApiClient.json_data(me_response)
    assert int(me["user_id"]) > 0
    assert isinstance(me.get("roles"), list) and me["roles"]
    assert isinstance(me.get("permissions"), list)

    routes_response = admin_client.get("/api/rbac/user/routes")
    routes_data = ReleaseApiClient.json_data(routes_response)
    route_paths = flatten_route_paths(routes_data["routes"])
    assert "/home" in route_paths
    assert "/settings" in route_paths
    assert "/role-permissions" in route_paths

    users_response = admin_client.get("/api/v3/rbac/users?page=1&page_size=20")
    users_data = ReleaseApiClient.json_data(users_response)
    assert users_data["total"] >= 1
    assert isinstance(users_data["items"], list)

    roles_response = admin_client.get("/api/v3/rbac/roles?page=1&page_size=20")
    roles_data = ReleaseApiClient.json_data(roles_response)
    assert roles_data["items"]
    role_id = int(roles_data["items"][0]["id"])
    role_users_response = admin_client.get(f"/api/v3/rbac/roles/{role_id}/users?page=1&page_size=1")
    role_users_data = ReleaseApiClient.json_data(role_users_response)
    assert role_users_data["page"] == 1
    assert role_users_data["page_size"] == 1
    assert "total" in role_users_data
    assert isinstance(role_users_data["items"], list)
    assert len(role_users_data["items"]) <= 1

    org_response = admin_client.get("/api/admin/users/organizations/tree?include_users=false")
    org_data = ReleaseApiClient.json_data(org_response)
    assert "organizations" in org_data
    assert org_data["total_organizations"] >= 1

    tenant_option_response = admin_client.get("/api/v3/tenants/options?feature_key=home.entry_module")
    tenant_option_data = ReleaseApiClient.json_data(tenant_option_response)
    assert tenant_option_data["total"] >= 1
