from channels.middleware import BaseMiddleware
from channels.db import database_sync_to_async
from urllib.parse import parse_qs


@database_sync_to_async
def get_user_from_token(token_key):
    from django.contrib.auth.models import AnonymousUser
    from account.models import User
    from rest_framework_simplejwt.tokens import AccessToken
    try:
        token = AccessToken(token_key)
        user_id = token.get("user_id")
        if user_id is None:
            return AnonymousUser()
        return User.objects.get(id=int(user_id))
    except Exception as e:
        print(f"JWT Auth error: {e}")
        from django.contrib.auth.models import AnonymousUser
        return AnonymousUser()


class JWTAuthMiddleware(BaseMiddleware):
    async def __call__(self, scope, receive, send):
        from django.contrib.auth.models import AnonymousUser
        query_string = scope.get("query_string", b"").decode()
        params = parse_qs(query_string)
        token_list = params.get("token", [])

        if token_list:
            scope["user"] = await get_user_from_token(token_list[0])
        else:
            scope["user"] = AnonymousUser()

        print(f"WS Auth: user={scope['user']}, authenticated={scope['user'].is_authenticated}")
        return await super().__call__(scope, receive, send)