from rest_framework import serializers
from .models import Cart
from decimal import Decimal

class CartSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Cart
        fields = (
            'id', 'user', 'quick_schedule',
            'pickup_type',
            'schedule_pickup_date', 'schedule_pickup_time',
            'contact_name', 'contact_mobile', 'pickup_instructions',
            'pickup_address', 'geo_location', 
            'order_details', 'premium_details', 'luxury_details',
            'total_quantity', 'total_final_price', 'currency_code',
            'created_at', 'updated_at'
        )
        read_only_fields = ('id', 'user', 'created_at', 'updated_at')

    def _validate_details(self, details, field_name):
        if not details:
            return
            
        if not isinstance(details, dict):
            raise serializers.ValidationError({field_name: 'Must be an object.'})

        for service_key, service_val in details.items():
            if not isinstance(service_val, dict):
                raise serializers.ValidationError({field_name: f'Service "{service_key}" must map to an object of categories.'})
            for category_key, items in service_val.items():
                if not isinstance(items, list):
                    raise serializers.ValidationError({field_name: f'Category "{category_key}" under service "{service_key}" must be a list of items.'})
                for idx, item in enumerate(items):
                    if not isinstance(item, dict):
                        raise serializers.ValidationError({field_name: f'Item at index {idx} in "{service_key}.{category_key}" must be an object.'})
                    # Basic required fields
                    required_fields = ['item_id', 'item_name', 'item_service', 'item_quantity']
                    for req in required_fields:
                        if req not in item:
                            raise serializers.ValidationError({field_name: f'Item at index {idx} missing field "{req}".'})

    def validate(self, data):
        if 'order_details' in data:
            self._validate_details(data['order_details'], 'order_details')
        if 'premium_details' in data:
            self._validate_details(data['premium_details'], 'premium_details')
        if 'luxury_details' in data:
            self._validate_details(data['luxury_details'], 'luxury_details')
        return data
