from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import serializers

from .models import CustomUser
from django.contrib.auth.models import Group
# User & Access Management Serializers

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ['id', 'name']
        
        
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['id', 'username', 'email', 'first_name', 'last_name', 'mfa_enabled', 'is_staff', 'is_active','groups']
        read_only_fields = ['is_staff', 'is_active'] # Admin manages these

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        
        print("User Groups:", user.groups.all())  # Check if groups are assigned
        print("Token before adding custom claims:", token)
        token['email'] = user.email

        token['username'] = user.username
        token['groups'] = list(user.groups.values_list('name', flat=True))  # Ensure groups are added correctly
        
        print("Token after adding custom claims:", token)
        
        return token
