"""
GraphQL middleware for JWT authentication.
"""
from graphql import GraphQLError
from jwt import InvalidTokenError

from .auth import get_bearer_token, validator


def _is_introspection(info) -> bool:
    """Возвращает True для любых introspection резолвов."""
    field = getattr(info, "field_name", "")
    parent = getattr(getattr(info, "parent_type", None), "name", "")
    return field.startswith("__") or parent.startswith("__")


class UserJWTMiddleware:
    """User endpoint - requires ID token."""

    def resolve(self, next, root, info, **kwargs):
        request = info.context
        if _is_introspection(info):
            return next(root, info, **kwargs)

        try:
            token = get_bearer_token(request)
            payload = validator.decode(token)
            request.user_id = payload.get('sub')
        except InvalidTokenError as exc:
            raise GraphQLError("Unauthorized") from exc

        return next(root, info, **kwargs)
