from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from core.security import verify_token
from core.context import set_user_context

class UserContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next) -> Response:
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            token = auth_header.split(" ")[1]
            try:
                # verify_token might raise exception if invalid, we catch it to not block request
                # but we won't have user context
                user_info = await verify_token(token)
                set_user_context(user_info)
            except Exception:
                # Log error or ignore
                pass
        
        try:
            response = await call_next(request)
        except Exception:
            # Re-raise the exception to let other middleware and handlers deal with it
            raise
        
        return response
