from rest_framework import serializers
from .models import Function
from paycode.models import Paycode

class FunctionSerializer(serializers.ModelSerializer):
    question_type_display = serializers.CharField(
        source='get_question_type_display',
        read_only=True
    )
    paycode_id = serializers.CharField(source='paycode.paycode', read_only=True)
    paycode_name = serializers.CharField(source='paycode.name', read_only=True)
    
    class Meta:
        model = Function
        fields = [
            'id', 'name', 'out', 'pre_function', 'break_flag', 'with_reason',
            'paycode', 'paycode_id', 'paycode_name',
            'function_ref_id', 'question_type', 'question_type_display',        
            'created_at', 'updated_at'
        ]
        extra_kwargs = {
            'paycode': {'required': False, 'allow_null': True}
        }
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def to_internal_value(self, data):
        """Handle paycode input - accept paycode field value (string) and convert to Paycode instance"""
        data = data.copy() if hasattr(data, 'copy') else dict(data)
        if 'paycode' in data:
            paycode_value = data['paycode']
            # If paycode is provided as a string (paycode field value), find the Paycode instance
            if isinstance(paycode_value, str) and paycode_value.strip():
                try:
                    paycode_instance = Paycode.objects.get(paycode=paycode_value)
                    data['paycode'] = paycode_instance.id  # Use the UUID id for the ForeignKey
                except Paycode.DoesNotExist:
                    raise serializers.ValidationError({'paycode': f"Paycode with code '{paycode_value}' not found"})
            elif not paycode_value or (isinstance(paycode_value, str) and not paycode_value.strip()):
                # Allow empty paycode - set to None
                data['paycode'] = None
        return super().to_internal_value(data)
    
    def to_representation(self, instance):
        """Customize the representation to include paycode details"""
        representation = super().to_representation(instance)
        # Include paycode details in the response if paycode exists
        if instance.paycode:
            representation['paycode_id'] = instance.paycode.paycode
            representation['paycode_name'] = instance.paycode.name
        else:
            representation['paycode_id'] = None
            representation['paycode_name'] = None
        return representation 