from django.db import transaction
from rest_framework import serializers

from gallery.models import Image
from review.models import Inquiries, InquiriesGallery


class InquiryGallerySerializer(serializers.Serializer):
    id = serializers.IntegerField()
    inquiry_id = serializers.IntegerField()
    created_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')
    attachment_file_name = serializers.CharField()
    attachment_suffix_url = serializers.CharField()

    def validate(self, data):
        data.update({
            'image': {
                'image': data.pop('attachment_suffix_url'),
                'title': data.pop('attachment_file_name'),
                'created': data.pop('created_at'),
            },
            'gallery': {
                'old_id': data.pop('id'),
                'inquiry': self.get_inquiry(data),
            },
        })
        data.pop('inquiry_id')
        return data

    def create(self, validated_data):
        try:
            with transaction.atomic():
                img = Image.objects.create(**validated_data['image'])
                gal = InquiriesGallery.objects.create(image=img, **validated_data['gallery'])
        except Exception as e:
            raise ValueError(f"Error creating InquiriesGallery with {validated_data}: {e}")
        else:
            return gal

    @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
