from apps.consultant.models import Consultant, ConsultantType

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer



class ConsultantListAPISerializer(ModelSerializer):
    type = serializers.CharField(source='type.name', allow_null=True,)
    created_by = serializers.CharField(source='get_created_by_full_name', read_only=True)

    class Meta:
        model = Consultant
        fields = ('id', 'name', 'type', 'phone_no', 'email', 'note', 'created_by', 'deleted_at',)
        read_only_fields = fields


class ConsultantSerializer(serializers.ModelSerializer):
    type = serializers.PrimaryKeyRelatedField(queryset=ConsultantType.objects.all())

    class Meta:
        model = Consultant
        fields = ('id', 'name', 'type', 'phone_no',)



class ConsultantStoreAPISerializer(ModelSerializer):
    type = serializers.CharField(required=True, write_only=True)

    class Meta:
        model = Consultant
        fields = ('id', 'name', 'type', 'phone_no', 'email', 'note',)

    def validate(self, attrs):
        if 'type' in attrs and attrs.get('type').isnumeric():
            consultant_type = ConsultantType.objects.filter(id=attrs['type']).first()

            if not consultant_type:
                raise serializers.ValidationError({'invalid_consultant': 'Please enter proper consultant!'})

        if Consultant.objects.filter(email=attrs.get('email')).exclude(id=self.instance.id if self.instance else None).exists():
            raise serializers.ValidationError({'email': 'A Consultant with this email already exists.'})

        return super().validate(attrs)


class ConsultantDeleteAPISerializer(ModelSerializer):
    class Meta:
        model = Consultant
        fields = ('id', 'name', 'type', 'phone_no',)
