"""
GraphQL middleware for JWT authentication.

This middleware runs for every GraphQL resolver and sets user_id/organization_id
on info.context based on the JWT token in Authorization header.
"""
from django.conf import settings
from jwt import InvalidTokenError

from .auth import get_bearer_token, scopes_from_payload, validator


class TeamJWTMiddleware:
    """
    Middleware for team-level operations (Access Token).
    Sets info.context.user_id, organization_id, and scopes.
    """

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

        # Skip if already processed
        if hasattr(request, '_team_jwt_processed'):
            return next(root, info, **kwargs)

        request._team_jwt_processed = True
        request.user_id = None
        request.organization_id = None
        request.team_uuid = None
        request.scopes = []

        try:
            token = get_bearer_token(request)
            payload = validator.decode(
                token,
                audience=getattr(settings, 'LOGTO_ORDERS_AUDIENCE', None),
            )
            request.user_id = payload.get('sub')
            request.organization_id = payload.get('organization_id')
            request.team_uuid = payload.get('team_uuid')  # Custom claim from Logto
            request.scopes = scopes_from_payload(payload)
        except InvalidTokenError:
            pass

        return next(root, info, **kwargs)
