"""
审计日志测试用例
"""

import pytest
import time
from api.audit_api import SysLogAPI


@pytest.mark.audit
@pytest.mark.regression
class TestLoginLog:
    """登录日志测试类"""

    @pytest.mark.asyncio
    async def test_create_login_log(self, authenticated_client):
        """测试创建登录日志"""
        api = SysLogAPI(authenticated_client)
        timestamp = int(time.time() * 1000)
        data = {
            "username": f"testuser_{timestamp}",
            "ip": "127.0.0.1",
            "location": "本地",
            "browser": "Chrome",
            "os": "Mac OS",
            "status": "0",
            "message": "登录成功"
        }

        response = await api.create_login_log(data)

        assert response.status_code == 201
        result = response.json()
        assert result["username"] == data["username"]

    @pytest.mark.asyncio
    async def test_get_all_login_logs(self, authenticated_client):
        """测试获取所有登录日志"""
        api = SysLogAPI(authenticated_client)

        response = await api.get_login_logs()

        assert response.status_code == 200
        assert isinstance(response.json(), list)

    @pytest.mark.asyncio
    async def test_get_login_log_by_id(self, authenticated_client):
        """测试根据ID获取登录日志"""
        api = SysLogAPI(authenticated_client)
        timestamp = int(time.time() * 1000)
        data = {
            "username": f"testuser_{timestamp}",
            "ip": "127.0.0.1",
            "status": "0",
            "message": "登录成功"
        }
        create_response = await api.create_login_log(data)
        log_id = create_response.json()["id"]

        response = await api.get_login_log_by_id(log_id)

        assert response.status_code == 200
        assert response.json()["id"] == log_id


@pytest.mark.audit
@pytest.mark.regression
class TestExceptionLog:
    """异常日志测试类"""

    @pytest.mark.asyncio
    async def test_create_exception_log(self, authenticated_client):
        """测试创建异常日志"""
        api = SysLogAPI(authenticated_client)
        timestamp = int(time.time() * 1000)
        data = {
            "title": f"测试异常_{timestamp}",
            "exceptionName": "NullPointerException",
            "exceptionMsg": "Null pointer at line 100",
            "methodName": "cn.novalon.manage.sys.service.UserService.getUser",
            "ip": "127.0.0.1",
            "exceptionStack": "java.lang.NullPointerException\\n    at..."
        }

        response = await api.create_exception_log(data)

        assert response.status_code == 201
        result = response.json()
        assert result["title"] == data["title"]

    @pytest.mark.asyncio
    async def test_get_all_exception_logs(self, authenticated_client):
        """测试获取所有异常日志"""
        api = SysLogAPI(authenticated_client)

        response = await api.get_exception_logs()

        assert response.status_code == 200
        assert isinstance(response.json(), list)

    @pytest.mark.asyncio
    async def test_get_exception_log_by_id(self, authenticated_client):
        """测试根据ID获取异常日志"""
        api = SysLogAPI(authenticated_client)
        timestamp = int(time.time() * 1000)
        data = {
            "title": f"测试异常_{timestamp}",
            "exceptionName": "NullPointerException",
            "exceptionMsg": "Null pointer"
        }
        create_response = await api.create_exception_log(data)
        log_id = create_response.json()["id"]

        response = await api.get_exception_log_by_id(log_id)

        assert response.status_code == 200
        assert response.json()["id"] == log_id
    
    @pytest.mark.asyncio
    async def test_get_login_logs_by_page_success(self, authenticated_client):
        """测试分页获取登录日志成功"""
        api = SysLogAPI(authenticated_client)
        
        for i in range(5):
            timestamp = int(time.time() * 1000) + i
            data = {
                "username": f"testuser_{i}",
                "ip": f"127.0.0.{i}",
                "status": "0",
                "message": "登录成功"
            }
            await api.create_login_log(data)
        
        response = await api.get_login_logs(page=0, size=10)
        
        assert response.status_code == 200
        data = response.json()
        assert "content" in data
        assert "totalElements" in data
        assert "totalPages" in data
        assert "currentPage" in data
        assert "pageSize" in data
        assert len(data["content"]) <= 10
    
    @pytest.mark.asyncio
    async def test_get_login_logs_by_page_with_sort(self, authenticated_client):
        """测试分页获取登录日志并排序成功"""
        api = SysLogAPI(authenticated_client)
        
        for i in range(3):
            timestamp = int(time.time() * 1000) + i
            data = {
                "username": f"sortuser_{i}",
                "ip": "127.0.0.1",
                "status": "0",
                "message": "登录成功"
            }
            await api.create_login_log(data)
        
        response = await api.get_login_logs_by_page(page=0, size=10, sort="username", order="asc")
        
        assert response.status_code == 200
        data = response.json()
        usernames = [log["username"] for log in data["content"]]
        assert usernames == sorted(usernames)
    
    @pytest.mark.asyncio
    async def test_get_login_logs_by_page_with_search(self, authenticated_client):
        """测试分页获取登录日志并搜索成功"""
        api = SysLogAPI(authenticated_client)
        
        timestamp1 = int(time.time() * 1000)
        data1 = {
            "username": "search_test_user",
            "ip": "127.0.0.1",
            "status": "0",
            "message": "登录成功"
        }
        await api.create_login_log(data1)
        
        timestamp2 = int(time.time() * 1000) + 1
        data2 = {
            "username": "other_user",
            "ip": "127.0.0.2",
            "status": "0",
            "message": "登录成功"
        }
        await api.create_login_log(data2)
        
        response = await api.get_login_logs_by_page(page=0, size=10, keyword="search")
        
        assert response.status_code == 200
        data = response.json()
        assert len(data["content"]) >= 1
        assert all("search" in log["username"] or "search" in log.get("ip", "") 
                  for log in data["content"])
    
    @pytest.mark.asyncio
    async def test_get_login_log_count_success(self, authenticated_client):
        """测试获取登录日志总数成功"""
        api = SysLogAPI(authenticated_client)
        
        initial_count_response = await api.get_login_log_count()
        initial_count = initial_count_response.json()
        
        timestamp = int(time.time() * 1000)
        data = {
            "username": f"count_test_user",
            "ip": "127.0.0.1",
            "status": "0",
            "message": "登录成功"
        }
        await api.create_login_log(data)
        
        final_count_response = await api.get_login_log_count()
        final_count = final_count_response.json()
        
        assert final_count == initial_count + 1
