from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework.exceptions import AuthenticationFailed
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser

# pakai custom auth
from webapp.api.auth.custom_jwt import CustomJWTAuthentication


class JWTFromCookieMiddleware(MiddlewareMixin):
    def __init__(self, get_response=None):
        self.get_response = get_response
        self.jwt_auth = CustomJWTAuthentication()  # 🔹 GANTI ke custom

    def process_request(self, request):
        if not request.path.startswith("/api/"):
            return None

        # Kalau sudah ada Authorization header → biarkan DRF
        if "HTTP_AUTHORIZATION" in request.META:
            return None

        # Kalau tidak ada header, coba ambil dari cookie
        access_token = request.COOKIES.get("access_token")
        if not access_token:
            return None

        request.META["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
        try:
            validated_token = self.jwt_auth.get_validated_token(access_token)
            request.user = self.jwt_auth.get_user(validated_token)
        except (InvalidToken, TokenError, AuthenticationFailed):
            request.user = AnonymousUser()
            request.META.pop("HTTP_AUTHORIZATION", None)
