from apps.contractor.models import ContractorType, Contractor

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer



class ContractorListAPISerializer(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 = Contractor
        fields = ('id', 'name', 'type', 'phone_no', 'email', 'created_by', 'deleted_at', 'note',)
        read_only_fields = fields


class ContractorSerializer(serializers.ModelSerializer):
    type = serializers.PrimaryKeyRelatedField(queryset=ContractorType.objects.all())

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



class ContractorStoreAPISerializer(ModelSerializer):
    type = serializers.CharField(required=True, write_only=True)
    class Meta:
        model = Contractor
        fields = ('id', 'name', 'type', 'phone_no', 'email', 'note',)

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

            if not contractor_type:
                raise serializers.ValidationError({'invalid_contractor': 'Please enter proper contractor!'})

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

        return super().validate(attrs)


class ContractorDeleteAPISerializer(ModelSerializer):
    class Meta:
        model = Contractor
        fields = ('id', 'name', 'type', 'phone_no',)
