from rest_framework import serializers

from core.apps.eggs.models import Broken, Group, History
from core.apps.eggs.models.monitoring import Monitoring
from core.http.models.user import User


class BrokenSerializer(serializers.ModelSerializer):
    class Meta:
        model = Broken
        fields = ["comment", "quantity", "group", "price"]

    def validate(self, data):
        group = Group.objects.get(id=data["group"].id)
        if data["quantity"] > group.quantity:
            raise serializers.ValidationError(
                "Miqdori guruh miqdoridan ko'p bo'lishi mumkin emas"
            )
        return data

    def create(self, validated_data):
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = User.objects.get(id=request.user.id)
            validated_data["user_id"] = user
        instance = Broken.objects.create(**validated_data)

        History.objects.create(
            content_object=instance,
            action="broken_created",
            user_id=instance.user_id,
            created_who=f"{instance.user_id.first_name} {instance.user_id.last_name}",
            created_by=instance.group.name,
            reason=f"Singan tuxum qo'shildi: {instance.quantity} ta",
            avatar=(
                instance.user_id.avatar if instance.user_id.avatar else None
            ),
        )
        Monitoring.objects.create(
            content_object=instance,
            action="broken_created",
            user_id=instance.user_id,
            created_who=f"{instance.user_id.first_name} {instance.user_id.last_name}",
            created_by=instance.group.name,
            reason=f"Singan tuxum qo'shildi: {instance.quantity} ta",
            comment="Chiqim",
            price=instance.price,
        )

        return instance
