# from rest_framework.authentication import BaseAuthentication
# from rest_framework.exceptions import AuthenticationFailed
# from rest_framework_simplejwt.tokens import AccessToken
# from accounts.models import Cliente
# from bson import ObjectId

# class ClienteJWTAuthentication(BaseAuthentication):
#     """Custom authentication class for Cliente using JWT tokens."""

#     def authenticate(self, request):
#         print("here in authentication.py")
#         """Authenticate a Cliente using JWT."""
#         auth_header = request.headers.get("Authorization")

#         if not auth_header or not auth_header.startswith("Bearer "):
#             print("❌ No token found in request headers")
#             return None  # No token provided

#         token = auth_header.split(" ")[1]  # Extract token

#         try:
#             # Decode JWT token
#             access_token = AccessToken(token)

#             # Debugging: Print the token payload
#             print(f"🔹 Decoded JWT Payload: {dict(access_token)}")

#             # Extract Cliente ID from `sub`
#             cliente_id = access_token.get("sub")
#             if not cliente_id:
#                 print("❌ Missing 'sub' field in token.")
#                 raise AuthenticationFailed("Missing 'sub' field in token.")

#             print(f"🔹 Extracted cliente_id: {cliente_id}")

#             # Fetch Cliente from MongoDB
#             cliente_data = Cliente.objects.mongo_find_one({"_id": ObjectId(cliente_id), "is_active": True})
#             if not cliente_data:
#                 print(f"❌ Cliente with ID {cliente_id} not found in MongoDB")
#                 raise AuthenticationFailed({"code": "user_not_found", "detail": "User not found"})

#             print(f"✅ Cliente found: {cliente_data}")

#             # Convert MongoDB data to Cliente model instance
#             cliente_data["id"] = str(cliente_data.pop("_id"))
#             cliente_instance = Cliente(**cliente_data)

#             print(f"✅ Cliente authenticated: {cliente_instance}")

#             return (cliente_instance, None)  # ✅ Return authenticated user

#         except Exception as e:
#             print(f"❌ Authentication Error: {e}")
#             raise AuthenticationFailed({"code": "authentication_failed", "detail": "Invalid authentication token."})

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from accounts.models import ClienteToken, Cliente
from rest_framework_simplejwt.tokens import AccessToken
from bson import ObjectId

class ClienteTokenAuthentication(BaseAuthentication):
    """Authenticate a Cliente using stored JWT token in MongoDB."""

    def authenticate(self, request):
        """Extract token from request and authenticate Cliente."""
        auth_header = request.headers.get("Authorization")

        if not auth_header or not auth_header.startswith("Bearer "):
            return None  # No token provided

        token_key = auth_header.split(" ")[1]  # Extract token

        try:
            # Search for the token in MongoDB
            token_obj = ClienteToken.objects.get(key=token_key)
            decoded_token = AccessToken(token_key)
            
            # Get cliente ID
            cliente_id = decoded_token.get("sub")
            if not cliente_id:
                raise AuthenticationFailed("Invalid token: missing `sub` field.")

            # Fetch Cliente from MongoDB
            cliente = Cliente.objects.get(id=ObjectId(cliente_id))

            return (cliente, token_obj)

        except ClienteToken.DoesNotExist:
            raise AuthenticationFailed("Invalid token.")
        except Exception as e:
            raise AuthenticationFailed(f"Authentication error: {str(e)}")







