from rest_framework import serializers
from .models import UserProfile
from django.db.models import Avg


class UserProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)
    email = serializers.CharField(source='user.email', read_only=True)
    user_type = serializers.CharField(source='user.user_type', read_only=True)

    class Meta:
        model = UserProfile
        fields = '__all__'
        read_only_fields = ('user', 'created_at', 'updated_at')

    # def validate_phone_number(self, value):
    #     """Validate unique phone number across all user profiles"""
    #     if value:  # Only check if phone number is provided
    #         # Check if another user profile already has this phone number
    #         existing_profile = UserProfile.objects.filter(phone_number=value).exclude(pk=self.instance.pk if self.instance else None)
    #         if existing_profile.exists():
    #             raise serializers.ValidationError("A user with this phone number already exists.")
    #     return value

    def validate_phone_number(self, value):
        """Validate phone number is unique across all profiles except current one"""
        if not value:
            return value

        qs = UserProfile.objects.filter(phone_number=value)
        if self.instance:
            qs = qs.exclude(pk=self.instance.pk)

        if qs.exists():
            raise serializers.ValidationError("A user with this phone number already exists.")
        return value

