from django.db.models import Sum
from rest_framework import serializers

from core.apps.eggs.models import AdditionalCost, History
from core.apps.eggs.models.monitoring import Monitoring
from core.http.serializers import UserSerializer


class AdditionalCostSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    total_price = serializers.SerializerMethodField()

    class Meta:
        model = AdditionalCost
        fields = ["id", "user", "reason", "price", "created_at", "total_price"]
        read_only_fields = ["created_at", "total_price"]
        extra_kwargs = {
            "user": {"required": False},
        }

    def create(self, validated_data):
        additional_cost = AdditionalCost.objects.create(**validated_data)
        user = self.context["request"].user
        if user is not None:
            additional_cost.user = user
            additional_cost.save()
            History.objects.create(
                content_object=additional_cost,
                action="additional_cost_created",
                user_id=user,
                created_who=f"{user.first_name} {user.last_name}",
                created_by=f"{user.first_name} {user.last_name}",
                reason=f"Qo'shimcha xarajat qo'shildi {additional_cost.price} so'm",
                comment=additional_cost.reason,
                avatar=user.avatar if user.avatar else None,
            )
            Monitoring.objects.create(
                content_object=additional_cost,
                action="additional_cost_created",
                user_id=user,
                created_who=f"{user.first_name} {user.last_name}",
                created_by=f"{user.first_name} {user.last_name}",
                reason=f"Qo'shimcha xarajat qo'shildi {additional_cost.price} so'm",
                comment="Chiqim",
                price=additional_cost.price,
            )
            return additional_cost
        else:
            raise serializers.ValidationError("User is not authenticated")

    def get_total_price(self, obj):
        return AdditionalCost.objects.aggregate(total_price=Sum("price"))[
            "total_price"
        ]
