from rest_framework import serializers

from review.models import Inquiries, GridItems


class GridItemsSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    created_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')
    inquiry_id = serializers.IntegerField()
    sub_item_name = serializers.CharField(allow_null=True, allow_blank=True)
    item_name = serializers.CharField(allow_null=True, allow_blank=True)
    value = serializers.FloatField(allow_null=True)
    desc = serializers.CharField(allow_null=True, allow_blank=True)
    dish_title = serializers.CharField(allow_null=True, allow_blank=True)

    def validate(self, data):
        data.update({
            'old_id': data.pop('id'),
            'created': data.pop('created_at'),
            'sub_name': data.pop('sub_item_name'),
            'name': data.pop('item_name'),
            'inquiry': self.get_inquiry(data),
        })
        data.pop('inquiry_id')
        return data

    def create(self, validated_data):
        try:
            return GridItems.objects.create(**validated_data)
        except Exception as e:
            raise ValueError(f"Error creating GridItems with {validated_data}: {e}")

    @staticmethod
    def get_inquiry(data):
        inquiry = Inquiries.objects.filter(old_id=data['inquiry_id']).first()
        if not inquiry:
            raise ValueError(f"Inquiries not found with old_id {data['inquiry_id']}")
        return inquiry
