"""Tests for app.core.middleware — TraceMiddleware"""

import pytest
from unittest.mock import AsyncMock, MagicMock


@pytest.mark.asyncio
async def test_trace_middleware_uses_existing_header():
    """If request has X-Request-Id, it should be reused"""
    from app.core.middleware import TraceMiddleware
    from starlette.requests import Request
    from starlette.responses import JSONResponse

    mock_request = MagicMock(spec=Request)
    mock_request.headers = {"X-Request-Id": "existing-id-123"}
    mock_request.state = MagicMock()

    mock_call_next = AsyncMock(return_value=JSONResponse(content={}))

    mw = TraceMiddleware(object())
    response = await mw.dispatch(mock_request, mock_call_next)

    assert mock_request.state.request_id == "existing-id-123"
    assert response.headers["X-Request-Id"] == "existing-id-123"


@pytest.mark.asyncio
async def test_trace_middleware_generates_new_id():
    """If no X-Request-Id header, a new one should be generated"""
    from app.core.middleware import TraceMiddleware
    from starlette.requests import Request
    from starlette.responses import JSONResponse

    mock_request = MagicMock(spec=Request)
    mock_request.headers = {}
    mock_request.state = MagicMock()

    mock_call_next = AsyncMock(return_value=JSONResponse(content={}))

    mw = TraceMiddleware(object())
    response = await mw.dispatch(mock_request, mock_call_next)

    assert mock_request.state.request_id is not None
    assert response.headers["X-Request-Id"] == mock_request.state.request_id
    assert len(response.headers["X-Request-Id"]) > 10
