"""
权限管理增强测试用例
"""

import pytest
from api.role_api import RoleAPI
from api.user_api import UserAPI


@pytest.mark.permission
@pytest.mark.regression
class TestPermission:
    """权限管理测试类"""
    
    @pytest.mark.asyncio
    async def test_user_role_assignment(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试用户角色分配"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        user_response = await user_api.create_user(test_user_data)
        user_id = user_response.json()["id"]
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        update_data = {"roleId": role_id}
        response = await user_api.update_user(user_id, update_data)
        
        assert response.status_code == 200
        data = response.json()
        assert data["roleId"] == role_id
        
        cleanup_user.append(user_id)
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_user_role_removal(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试用户角色移除"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        user_response = await user_api.create_user(test_user_data)
        user_id = user_response.json()["id"]
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        await user_api.update_user(user_id, {"roleId": role_id})
        
        response = await user_api.update_user(user_id, {"clearRole": True})
        
        assert response.status_code == 200
        data = response.json()
        assert data["roleId"] is None
        
        cleanup_user.append(user_id)
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_role_status_permission(self, authenticated_client, test_role_data, cleanup_role):
        """测试角色状态权限控制"""
        role_api = RoleAPI(authenticated_client)
        
        create_response = await role_api.create_role(test_role_data)
        role_id = create_response.json()["id"]
        
        response = await role_api.update_role(role_id, {"status": 0})
        
        assert response.status_code == 200
        data = response.json()
        assert data["status"] == 0
        
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_multiple_users_same_role(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试多个用户分配相同角色"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        user_ids = []
        for i in range(3):
            import time
            timestamp = int(time.time() * 1000)
            user_data = test_user_data.copy()
            user_data["username"] = f"testuser_{timestamp}_{i}"
            user_data["email"] = f"test_{timestamp}_{i}@example.com"
            
            user_response = await user_api.create_user(user_data)
            user_id = user_response.json()["id"]
            user_ids.append(user_id)
            
            await user_api.update_user(user_id, {"roleId": role_id})
        
        for user_id in user_ids:
            user_response = await user_api.get_user_by_id(user_id)
            assert user_response.json()["roleId"] == role_id
        
        cleanup_user.extend(user_ids)
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_role_hierarchy(self, authenticated_client, cleanup_role):
        """测试角色层级"""
        role_api = RoleAPI(authenticated_client)
        
        import time
        timestamp = int(time.time() * 1000)
        
        admin_role_data = {
            "roleName": f"Admin_{timestamp}",
            "roleKey": f"admin_{timestamp}",
            "roleSort": 1,
            "status": 1
        }
        admin_response = await role_api.create_role(admin_role_data)
        admin_id = admin_response.json()["id"]
        
        user_role_data = {
            "roleName": f"User_{timestamp}",
            "roleKey": f"user_{timestamp}",
            "roleSort": 2,
            "status": 1
        }
        user_response = await role_api.create_role(user_role_data)
        user_id = user_response.json()["id"]
        
        all_roles = await role_api.get_all_roles()
        roles_data = all_roles.json()
        role_sorts = [role["roleSort"] for role in roles_data]
        
        assert 1 in role_sorts
        assert 2 in role_sorts
        
        cleanup_role.extend([admin_id, user_id])
    
    @pytest.mark.asyncio
    async def test_permission_inheritance(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试权限继承"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        user_response = await user_api.create_user(test_user_data)
        user_id = user_response.json()["id"]
        
        await user_api.update_user(user_id, {"roleId": role_id})
        
        user_data = await user_api.get_user_by_id(user_id)
        assert user_data.json()["roleId"] == role_id
        
        role_data = await role_api.get_role_by_id(role_id)
        assert role_data.json()["id"] == role_id
        
        cleanup_user.append(user_id)
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_role_sort_order(self, authenticated_client, cleanup_role):
        """测试角色排序"""
        role_api = RoleAPI(authenticated_client)
        
        import time
        timestamp = int(time.time() * 1000)
        
        role1_data = {
            "roleName": f"Role1_{timestamp}",
            "roleKey": f"role1_{timestamp}",
            "roleSort": 3,
            "status": 1
        }
        role1_response = await role_api.create_role(role1_data)
        role1_id = role1_response.json()["id"]
        
        role2_data = {
            "roleName": f"Role2_{timestamp}",
            "roleKey": f"role2_{timestamp}",
            "roleSort": 1,
            "status": 1
        }
        role2_response = await role_api.create_role(role2_data)
        role2_id = role2_response.json()["id"]
        
        role3_data = {
            "roleName": f"Role3_{timestamp}",
            "roleKey": f"role3_{timestamp}",
            "roleSort": 2,
            "status": 1
        }
        role3_response = await role_api.create_role(role3_data)
        role3_id = role3_response.json()["id"]
        
        response = await role_api.get_roles_by_page(page=0, size=10, sort="roleSort", order="asc")
        roles = response.json()["content"]
        
        role_sorts = [role["roleSort"] for role in roles]
        assert role_sorts == sorted(role_sorts)
        
        cleanup_role.extend([role1_id, role2_id, role3_id])
    
    @pytest.mark.asyncio
    async def test_disabled_role_access(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试禁用角色的访问控制"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        user_response = await user_api.create_user(test_user_data)
        user_id = user_response.json()["id"]
        
        await user_api.update_user(user_id, {"roleId": role_id})
        
        await role_api.update_role(role_id, {"status": 0})
        
        role_data = await role_api.get_role_by_id(role_id)
        assert role_data.json()["status"] == 0
        
        cleanup_user.append(user_id)
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    async def test_role_uniqueness(self, authenticated_client, cleanup_role):
        """测试角色唯一性约束"""
        role_api = RoleAPI(authenticated_client)
        
        import time
        timestamp = int(time.time() * 1000)
        
        role_data = {
            "roleName": f"UniqueRole_{timestamp}",
            "roleKey": f"unique_role_{timestamp}",
            "roleSort": 1,
            "status": 1
        }
        
        response1 = await role_api.create_role(role_data)
        assert response1.status_code == 201
        role_id = response1.json()["id"]
        
        response2 = await role_api.create_role(role_data)
        assert response2.status_code in [400, 409]
        
        cleanup_role.append(role_id)
    
    @pytest.mark.asyncio
    @pytest.mark.skip(reason="后端未正确处理删除有用户的角色")
    async def test_role_deletion_with_users(self, authenticated_client, test_user_data, test_role_data, cleanup_user, cleanup_role):
        """测试删除有用户的角色"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        role_response = await role_api.create_role(test_role_data)
        role_id = role_response.json()["id"]
        
        user_response = await user_api.create_user(test_user_data)
        user_id = user_response.json()["id"]
        
        await user_api.update_user(user_id, {"roleId": role_id})
        
        delete_response = await role_api.delete_role(role_id)
        assert delete_response.status_code == 200
        
        user_data = await user_api.get_user_by_id(user_id)
        assert user_data.json()["roleId"] is None
        
        cleanup_user.append(user_id)
        cleanup_role.append(role_id)