from rest_framework import serializers

from core.apps.eggs.models import Debt, Market, History, Notification
from core.apps.eggs.models.debt import DebtTypeEnum
from core.apps.eggs.models.monitoring import Monitoring
from core.http.models import User
from core.apps.eggs.tasks.send_sms import send_sms_msg




class DebtSerializer(serializers.ModelSerializer):
    class Meta:
        model = Debt
        fields = [
            "market",
            "debt_price",
            "debt_type",
            "created_at",
            "updated_at",
        ]

    def validate(self, data):
        market = Market.objects.get(id=data["market"].id)
        if (
            data["debt_price"] > market.debt_unpaid
            and data.get("debt_type", None) == DebtTypeEnum.LOST.value
        ):
            raise serializers.ValidationError(
                {
                    "debt_price": "Qarz narxi to'lanmagan qarzdan yuqori bo'lishi mumkin emas."
                }
            )
        return data

    def create(self, validated_data):
        instance = Debt.objects.create(**validated_data)

        request = self.context.get("request")
        request_user = request.user

        full_name = f"{request_user.first_name} {request_user.last_name}"

        History.objects.create(
            content_object=instance,
            action="debt_created",
            user_id=request_user,
            created_who=full_name,
            created_by=instance.market.name,
            avatar=instance.market.avatar,
            reason=f"Qarz yechildi {instance.debt_price}",
            comment=f"Qarz yechildi {instance.debt_price}",
        )
        Monitoring.objects.create(
            content_object=instance,
            action="debt_created",
            user_id=request_user,
            created_who=full_name,
            created_by=instance.market.name,
            reason=f"Qarz yechildi {instance.debt_price}",
            comment="Kirim",
            price=instance.debt_price,
        )
        notification_users = User.objects.filter(role="admin")
        for user in notification_users:
            Notification.objects.create(
                user=user,
                title=f"Qarz muvaffaqiyatli yechildi {instance.debt_price} so'm",
                body=f"Qarz muvaffaqiyatli yechildi {instance.market.name} dan {instance.debt_price} so'm",
            )

        message = f"Hurmatli {instance.market.user_id.first_name} {instance.market.user_id.last_name} , Sizning  Gold-eggs.uz tuxum yetkazib berish xizmati ilovasidagi xaridingizga {instance.debt_price} so'm qarz  yechildi Umumiy balans: {instance.market.debt_unpaid} so'm Batafsil: +998914249515"

        try:
            send_sms_msg.delay(instance.market.user_id.phone, message)
        except Exception:
            pass
        return instance
