import pytest
from unittest.mock import AsyncMock, MagicMock
from fastapi import HTTPException
from src.middleware import RequestValidationMiddleware

@pytest.mark.asyncio
async def test_request_validation_middleware_query_length():
    middleware = RequestValidationMiddleware(app=MagicMock())
    request = MagicMock()
    # Mocking request.url.query
    request.url.query = "a" * 2001
    
    with pytest.raises(HTTPException) as excinfo:
        await middleware.dispatch(request, AsyncMock())
    assert excinfo.value.status_code == 414

@pytest.mark.asyncio
async def test_request_validation_middleware_too_many_params():
    middleware = RequestValidationMiddleware(app=MagicMock())
    request = MagicMock()
    request.url.query = "a=1"
    # Mocking request.query_params.multi_items()
    request.query_params.multi_items.return_value = [("param", "val")] * 51
    
    with pytest.raises(HTTPException) as excinfo:
        await middleware.dispatch(request, AsyncMock())
    assert excinfo.value.status_code == 400
    assert "Too many query parameters" in excinfo.value.detail

@pytest.mark.asyncio
async def test_request_validation_middleware_pagination_logic():
    middleware = RequestValidationMiddleware(app=MagicMock())
    request = MagicMock()
    request.url.query = "size=55"
    request.query_params.multi_items.return_value = [("size", "55")]
    request.headers = {}
    
    with pytest.raises(HTTPException) as excinfo:
        await middleware.dispatch(request, AsyncMock())
    assert excinfo.value.status_code == 400
    assert "cannot exceed 50" in excinfo.value.detail

    request.query_params.multi_items.return_value = [("size", "7")]
    with pytest.raises(HTTPException) as excinfo:
        await middleware.dispatch(request, AsyncMock())
    assert "must be a multiple of 5" in excinfo.value.detail
