from rest_framework import serializers
from .models import ServiceRequest

class ServiceRequestSerializer(serializers.ModelSerializer):
    total_price = serializers.DecimalField(max_digits=12, decimal_places=2, required=False, default=0)
    # Allow clients to send 'pickup_address' to match Booking payload structure
    pickup_address = serializers.JSONField(write_only=True, required=False)

    class Meta:
        model = ServiceRequest
        fields = '__all__'
        read_only_fields = ('request_id', 'user', 'status', 'created_at', 'updated_at')

    def create(self, validated_data):
        # Map pickup_address to service_address if provided
        if 'pickup_address' in validated_data:
            validated_data['service_address'] = validated_data.pop('pickup_address')

        # Assign current user
        validated_data['user'] = self.context['request'].user
        
        # If contact info is missing, default to user info
        if not validated_data.get('contact_name'):
            validated_data['contact_name'] = validated_data['user'].get_full_name() or validated_data['user'].username
        if not validated_data.get('contact_mobile'):
            # Fallback to username if it looks like a mobile number
            username = validated_data['user'].username
            validated_data['contact_mobile'] = username if username.isdigit() else ""

        return super().create(validated_data)

    def update(self, instance, validated_data):
        # Map pickup_address to service_address if provided
        if 'pickup_address' in validated_data:
            validated_data['service_address'] = validated_data.pop('pickup_address')
            
        return super().update(instance, validated_data)
