"""
测试数据管理器使用示例
"""

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


@pytest.mark.example
@pytest.mark.regression
class TestDataManagerExample:
    """测试数据管理器使用示例"""
    
    @pytest.mark.asyncio
    async def test_create_and_cleanup_users(self, authenticated_client, test_data_manager):
        """演示测试数据管理器的使用"""
        user_api = UserAPI(authenticated_client)
        
        timestamp = int(time.time() * 1000)
        
        for i in range(3):
            user_data = {
                "username": f"managed_user_{timestamp}_{i}",
                "password": "Test123!@#",
                "email": f"managed_{timestamp}_{i}@example.com",
                "status": 1
            }
            
            response = await user_api.create_user(user_data)
            assert response.status_code == 201
            user_id = response.json()["id"]
            
            test_data_manager.add_user(user_id)
        
        cleanup_count = test_data_manager.get_stats()
        assert cleanup_count["users"] == 3
        
        all_users = await user_api.get_all_users()
        assert all_users.status_code == 200
        
        await test_data_manager.cleanup_all()
        
        final_count = test_data_manager.get_stats()
        assert final_count["users"] == 0
    
    @pytest.mark.asyncio
    async def test_multiple_resources_cleanup(self, authenticated_client, test_data_manager):
        """演示多资源清理"""
        user_api = UserAPI(authenticated_client)
        role_api = RoleAPI(authenticated_client)
        
        timestamp = int(time.time() * 1000)
        
        role_data = {
            "roleName": f"Managed_Role_{timestamp}",
            "roleKey": f"managed_role_{timestamp}",
            "roleSort": 1,
            "status": 1
        }
        
        role_response = await role_api.create_role(role_data)
        assert role_response.status_code == 201
        role_id = role_response.json()["id"]
        test_data_manager.add_role(role_id)
        
        for i in range(2):
            user_data = {
                "username": f"role_user_{timestamp}_{i}",
                "password": "Test123!@#",
                "email": f"role_user_{timestamp}_{i}@example.com",
                "status": 1
            }
            
            user_response = await user_api.create_user(user_data)
            assert user_response.status_code == 201
            user_id = user_response.json()["id"]
            test_data_manager.add_user(user_id)
            
            await user_api.update_user(user_id, {"roleId": role_id})
        
        cleanup_count = test_data_manager.get_stats()
        assert cleanup_count["roles"] == 1
        assert cleanup_count["users"] == 2
        
        await test_data_manager.cleanup_all()
        
        final_count = test_data_manager.get_stats()
        assert final_count["roles"] == 0
        assert final_count["users"] == 0