from rest_framework_simplejwt.authentication import JWTAuthentication

from .cookies import ACCESS_COOKIE_NAME


class CookieJWTAuthentication(JWTAuthentication):
    """
    Reads the JWT from the Authorization header first (the Flutter mobile
    client, which still receives tokens in the login response body and
    sends them back as a Bearer header), falling back to the httpOnly
    access_token cookie (the three web SPAs, which never see the raw token
    value at all — see cookies.py). Same validation either way; only where
    the raw token string comes from differs.
    """

    def authenticate(self, request):
        header = self.get_header(request)
        raw_token = self.get_raw_token(header) if header is not None else None
        if raw_token is None:
            raw_token = request.COOKIES.get(ACCESS_COOKIE_NAME)
        if raw_token is None:
            return None

        validated_token = self.get_validated_token(raw_token)
        return self.get_user(validated_token), validated_token
