from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed


class SessionBoundJWTAuthentication(JWTAuthentication):
    """
    Extends JWTAuthentication to reject access tokens whose session has been
    force-logged-out by a school admin. Tokens that don't carry a session_token
    claim (e.g. school-admin tokens) pass through unchanged.
    """

    def get_validated_token(self, raw_token):
        validated = super().get_validated_token(raw_token)

        session_token = validated.get("session_token")
        if not session_token:
            return validated

        from master_admin.models import UserSession

        active = UserSession.objects.using("default").filter(
            session_token=session_token, is_active=True
        ).exists()

        if not active:
            raise AuthenticationFailed(
                "Your session has been terminated. Please log in again.",
                code="session_terminated",
            )

        return validated
