from rest_framework import serializers

from comment.models import Comment, User
from establishment.models import Establishment


class CommentSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    comment = serializers.CharField()
    mark = serializers.DecimalField(max_digits=4, decimal_places=2, allow_null=True)
    account_id = serializers.IntegerField()
    establishment_id = serializers.CharField()

    def validate(self, data):
        data.update({
            'old_id': data.pop('id'),
            'text': data.pop('comment'),
            'mark': self.get_mark(data),
            'content_object': self.get_content_object(data),
            'user': self.get_account(data),
        })
        data.pop('establishment_id')
        data.pop('account_id')
        return data

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

    @staticmethod
    def get_content_object(data):
        establishment = Establishment.objects.filter(old_id=data['establishment_id']).first()
        if not establishment:
            raise ValueError(f"Establishment not found with old_id {data['establishment_id']}: ")
        return establishment

    @staticmethod
    def get_account(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

    @staticmethod
    def get_mark(data):
        if not data['mark']:
            return None
        return data['mark'] * -1 if data['mark'] < 0 else data['mark']
