from rest_framework import serializers
from crm.models import CollectionData, Lead
from subscriptions.models import Profile, SalesPersons

class CollectionDataSerializer(serializers.ModelSerializer):
    assigned_to_name = serializers.SerializerMethodField()
    created_by_name = serializers.SerializerMethodField()

    def get_assigned_to_name(self, obj):
        return obj.assigned_to.profiles.name if obj.assigned_to else None

    def get_created_by_name(self, obj):
        return obj.created_by.name if obj.created_by else None

    class Meta:
        model = CollectionData
        fields = '__all__'
        read_only_fields = ('id', 'created_at', 'updated_at')

class LeadSerializer(serializers.ModelSerializer):
    collection_data = serializers.PrimaryKeyRelatedField(
        queryset=CollectionData.objects.all(),
        source='collections',
        required=False
    )

    assigned_to_name = serializers.SerializerMethodField()
    created_by_name = serializers.SerializerMethodField()

    def get_assigned_to_name(self, obj):
        return obj.assigned_to.profiles.name if obj.assigned_to else None

    def get_created_by_name(self, obj):
        return obj.created_by.name if obj.created_by else None
    
    class Meta:
        model = Lead
        fields = '__all__'
        read_only_fields = ('id', 'created_at', 'updated_at', 'converted_date')
        extra_kwargs = {
            # Treat non-required fields as optional at API layer
            'email': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'phone': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'mobile': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'address': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'city': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'state': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'zip_code': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'country': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'company': { 'required': False, 'allow_null': True, 'allow_blank': True },
            'first_name': { 'required': False, 'allow_blank': True },
            'last_name': { 'required': False, 'allow_blank': True },
        }

    def validate(self, attrs):
        # Enforce required fields: company, first_name, last_name, mobile, country
        instance = getattr(self, 'instance', None)
        def get_val(key):
            if key in attrs:
                return attrs.get(key)
            if instance is not None:
                return getattr(instance, key)
            return None

        required_fields = ['company', 'first_name', 'last_name', 'mobile', 'country']
        missing = []
        for key in required_fields:
            val = get_val(key)
            if val is None or (isinstance(val, str) and not val.strip()):
                missing.append(key)

        if missing:
            # Human-friendly field names
            pretty = ', '.join([k.replace('_', ' ').title() for k in missing])
            raise serializers.ValidationError({ 'detail': f"Missing required fields: {pretty}" })

        return attrs

class ConvertCollectionToLeadSerializer(serializers.Serializer):
    collection_id = serializers.UUIDField()
    assigned_to = serializers.PrimaryKeyRelatedField(
        queryset=SalesPersons.objects.all(),
        required=False
    )