from __future__ import annotations

import pytest

from .conftest import SeededUser, TenantSeed
from .helpers import ReleaseApiClient


def _set_module_tenants(admin_client: ReleaseApiClient, module_id: int, module_name: str, tenants: list[TenantSeed], path: str) -> dict:
    payload = {
        "name": module_name,
        "description": "pytest release acceptance only",
        "path": path,
        "route_path": path,
        "tenants": [
            {
                "tenant_code": tenant.tenant_code,
                "tenant_name": tenant.tenant_name,
                "enabled": True,
                "sort_order": index,
            }
            for index, tenant in enumerate(tenants, start=1)
        ],
    }
    response = admin_client.put(f"/api/v3/entry-modules/{module_id}", json=payload, expected_status=200)
    return ReleaseApiClient.json_data(response)


def _home_module_names(client: ReleaseApiClient) -> list[str]:
    response = client.get("/api/home/entry-modules")
    modules = ReleaseApiClient.json_data(response)
    return [str(item.get("name") or "") for item in modules]


@pytest.mark.release
def test_g2_tenant_detail_and_user_tenant_switch(
    admin_client: ReleaseApiClient,
    anonymous_client: ReleaseApiClient,
    tenant_a: TenantSeed,
    tenant_common_user_a: SeededUser,
) -> None:
    detail_response = admin_client.get(f"/api/v3/tenants/{tenant_a.tenant_code}")
    detail = ReleaseApiClient.json_data(detail_response)
    assert detail["tenant_code"] == tenant_a.tenant_code
    assert detail["tenant_name"] == tenant_a.tenant_name
    assert "home.entry_module" in detail["feature_keys"]

    switch_response = admin_client.put(
        f"/api/v3/rbac/users/{tenant_common_user_a.user_id}/tenant",
        json={"tenant_code": tenant_a.tenant_code},
        expected_status=200,
    )
    switch_data = ReleaseApiClient.json_data(switch_response)
    assert switch_data["tenant_code"] == tenant_a.tenant_code

    relogin = anonymous_client.login_oauth(
        sub=tenant_common_user_a.sub,
        username=tenant_common_user_a.username,
        nickname=tenant_common_user_a.nickname,
        ou_id=f"pytest-{tenant_a.tenant_code.lower()}",
        ou_name=f"{tenant_a.tenant_name}测试组织",
        area=tenant_a.tenant_name,
    )
    assert relogin["user_info"]["tenant_code"] == tenant_a.tenant_code


@pytest.mark.release
def test_g3_entry_module_visibility_follows_tenant_assignment(
    admin_client: ReleaseApiClient,
    release_entry_module: dict,
    release_config,
    tenant_a: TenantSeed,
    tenant_b: TenantSeed,
    common_api_a: ReleaseApiClient,
    common_api_b: ReleaseApiClient,
) -> None:
    module_id = int(release_entry_module["id"])
    module_name = str(release_entry_module["name"])

    _set_module_tenants(admin_client, module_id, module_name, [tenant_b], release_config.module_path)
    names_a = _home_module_names(common_api_a)
    names_b = _home_module_names(common_api_b)
    assert module_name not in names_a
    assert module_name in names_b

    _set_module_tenants(admin_client, module_id, module_name, [tenant_a, tenant_b], release_config.module_path)
    names_a = _home_module_names(common_api_a)
    names_b = _home_module_names(common_api_b)
    assert module_name in names_a
    assert module_name in names_b
