from drf_spectacular.extensions import OpenApiAuthenticationExtension
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.authentication import JWTAuthentication


class ActiveUserJWTAuthentication(JWTAuthentication):
    """
    Reject JWTs for accounts whose business status is no longer active.
    """

    def get_user(self, validated_token):
        user = super().get_user(validated_token)

        if getattr(user, "status", None) != user.Status.ACTIVE:
            raise AuthenticationFailed(
                "User account is not active.",
                code="user_inactive",
            )

        return user


class ActiveUserJWTAuthenticationScheme(OpenApiAuthenticationExtension):
    target_class = "users.authentication.ActiveUserJWTAuthentication"
    name = "jwtAuth"

    def get_security_definition(self, auto_schema):
        return {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT",
        }
