"""Request ID middleware for request tracing."""

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

from app.core.log_context import set_request_id


class RequestIDMiddleware(BaseHTTPMiddleware):
    """Middleware to add unique request ID to each request."""

    async def dispatch(self, request: Request, call_next):
        # Generate or retrieve request ID (short form keeps logs readable)
        request_id = request.headers.get("X-Request-ID") or uuid.uuid4().hex[:8]

        # Add request ID to request state + logging context (so every log line
        # for this request carries it — grep one id to follow the whole request).
        request.state.request_id = request_id
        set_request_id(request_id)

        # Process request
        response = await call_next(request)

        # Add request ID to response headers
        response.headers["X-Request-ID"] = request_id

        return response

