import jwt
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin

from core.http.models import User


class JWTFCMMiddleware(MiddlewareMixin):
    def process_request(self, request):
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            token = auth_header.split(" ")[1]
            try:
                payload = jwt.decode(
                    token, settings.SECRET_KEY, algorithms=["HS256"]
                )
                user_id = payload.get("user_id")
                fcm_token = request.headers.get("FCM-Token")
                if user_id:
                    user = User.objects.get(id=user_id)
                    if fcm_token:
                        user.fcm_token = fcm_token
                        user.save()
            except jwt.ExpiredSignatureError:
                pass
            except jwt.InvalidTokenError:
                pass
