from starlette.middleware.base import BaseHTTPMiddleware
from urllib.request import Request

from app.common.jwt_check import check_token

from app.common.logger_config import logger_http


class LoggerMiddleware(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        method = request.method
        path = request.url.path
        token = request.headers.get("Authorization")
        user_id = None
        if token:
            decoded_payload = check_token(token)
            user_id = decoded_payload['user_id']
        logger_http.info(f"Path: {path},UserId: {user_id}, Method: {method}")
        response = await call_next(request)
        return response