"""Request/response middleware.

Currently includes request ID injection to support end-to-end tracing
across logs and downstream systems.
"""

import uuid
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

from .config import settings


class RequestIDMiddleware(BaseHTTPMiddleware):
    """Attach a request ID to each request and echo it in the response.

    - If the incoming request already includes the configured header,
      that value is reused.
    - Otherwise a UUID is generated.
    - The request ID is stored on `request.state` and added to the response.
    """

    async def dispatch(self, request: Request, call_next):
        header_name = settings.request_id_header
        request_id = request.headers.get(header_name) or str(uuid.uuid4())
        request.state.request_id = request_id
        response: Response = await call_next(request)
        response.headers[header_name] = request_id
        return response
