from fastapi import Request, status
from fastapi.responses import JSONResponse
from ..endpoints.routes import get_safe_endpoint_urls
from ..config import api_config


async def token_middleware(request: Request, call_next):

    base_url = request.url.path
    safe_endpoints = [_[0] for _ in get_safe_endpoint_urls()]
    if base_url in safe_endpoints:
        return await call_next(request)

    token = request.headers.get(api_config.ACCESS_TOKEN_TAG, None)
    if not token:
        return JSONResponse(
            content={
                "error": "EYS_0002",
            },
            status_code=status.HTTP_401_UNAUTHORIZED,
        )

    response = await call_next(request)
    return response
