from rest_framework import serializers

from account.models import User
from review.models import Inquiries, Review


class InquiriesSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    comment = serializers.CharField(allow_null=True, allow_blank=True)
    final_comment = serializers.CharField(allow_null=True, allow_blank=True)
    mark = serializers.FloatField(allow_null=True)
    created_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')
    review_id = serializers.IntegerField()

    attachment_content_type = serializers.CharField(allow_null=True, allow_blank=True)
    attachment_suffix_url = serializers.CharField(allow_null=True, allow_blank=True)

    account_id = serializers.IntegerField(allow_null=True)

    bill_content_type = serializers.CharField(allow_null=True, allow_blank=True)
    bill_suffix_url = serializers.CharField(allow_null=True, allow_blank=True)

    price = serializers.DecimalField(max_digits=7, decimal_places=2, allow_null=True)
    moment = serializers.CharField(allow_null=True, allow_blank=True)
    published = serializers.IntegerField(allow_null=True)

    decibels = serializers.CharField(allow_null=True, allow_blank=True)
    nomination = serializers.CharField(allow_null=True, allow_blank=True)
    nominee = serializers.CharField(allow_null=True, allow_blank=True)

    def validate(self, data):
        data.update({
            'old_id': data.pop('id'),
            'review': self.get_review(data),
            'created': data.pop('created_at'),
            'published': bool(data['published']),
            'moment': self.get_moment(data),
            'author': self.get_author(data),
            'attachment_file': data['attachment_suffix_url'] if data['attachment_content_type'] else '',
            'bill_file': data['bill_suffix_url'] if data['bill_content_type'] else '',
        })
        data.pop('review_id')
        data.pop('account_id')
        data.pop('attachment_suffix_url')
        data.pop('bill_suffix_url')
        return data

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

    @staticmethod
    def get_review(data):
        review = Review.objects.filter(old_id=data['review_id']).first()
        if not review:
            raise ValueError(f"Review not found with old_id {data['review_id']}")
        return review

    @staticmethod
    def get_moment(data):
        moments = {
            'lanch': Inquiries.LUNCH,
            'diner': Inquiries.DINER,
        }
        moment = data['moment']
        return moments.get(moment, Inquiries.NONE)

    @staticmethod
    def get_author(data):
        user = User.objects.filter(old_id=data['account_id']).first()
        if not user:
            raise ValueError(f"User account not found with old_id {data['account_id']}")
        return user
