"""
Courier Product serializer
"""

from rest_framework import serializers

from core.apps.eggs import models
from core.apps.eggs.serializers import group
from core.apps.eggs.serializers import courier
from core.apps.eggs.models import History
from django.utils.translation import gettext as _
from django.contrib.auth import get_user_model


class CourierProductSerializer(serializers.ModelSerializer):
    courier = courier.CourierSerializer(read_only=True, source="courier_id")
    group = group.GroupSerializer(read_only=True, source="group_id")

    class Meta:
        model = models.CourierProduct
        fields = ("id", "group", "count", "courier")

    def list(self, request):
        user_id = request.user.id
        courier_product = models.CourierProduct.objects.filter(
            courier_id=user_id, count__gt=0
        )

        return courier_product


User = get_user_model()


class CourierProductCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CourierProduct
        fields = ("count", "group_id")

    def validate(self, data):
        group = models.Group.objects.get(id=data["group_id"].id)

        if data["count"] > group.quantity:
            raise serializers.ValidationError(
                "Guruh sonidan ko'p bo'lishi mumkin emas."
            )

        return data

    def create(self, validated_data):
        user_id = self.context["request"].user.id
        courier = models.Courier.objects.get(user_id=user_id)
        courier_product = models.CourierProduct.objects.create(
            courier_id=courier, **validated_data
        )

        user = User.objects.get(id=user_id)

        History.objects.create(
            user_id=user,
            action="courier_product_created",
            created_who=f"{courier.user_id.first_name} {courier.user_id.last_name}",
            created_by=courier_product.group_id.name,
            object_id=courier_product.id,
            content_object=courier_product,
            reason=_(f"Kuryer mahsulot oldi {courier_product.count} ta"),
            avatar=user.avatar if user.avatar else None,
        )

        return courier_product


class CourierProductReturnSerializer(serializers.ModelSerializer):
    data = CourierProductCreateSerializer(many=True)

    class Meta:
        model = models.CourierProduct
        fields = ("data",)

    def create(self, validated_data):
        data = validated_data.pop("data", [])
        courier_products = []
        for item in data:
            courier_product = CourierProductCreateSerializer(
                context=self.context
            ).create(item)
            courier_product.save()
            courier_products.append(courier_product)

        return {"data": courier_products}

    def to_representation(self, instance):
        data = instance.get("data", [])
        return {
            "data": [
                {
                    "id": product.id,
                    "group": group.GroupSerializer(product.group_id).data,
                    "count": product.count,
                    "courier": courier.CourierSerializer(
                        product.courier_id
                    ).data,  # noqa
                }
                for product in data
            ]
        }
