from rest_framework import serializers

from core.apps.eggs import models
from core.http.models import User


class AddSkladSerializer(serializers.ModelSerializer):
    sklad_id = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "sklad_id",
            "id",
            "first_name",
            "last_name",
            "phone",
            "username",
            "role",
            "avatar",
            "password",
        )

    def create(self, validated_data):
        validated_data["role"] = "sklad"
        user = User.objects.create_user(**validated_data)
        sklad = models.Sklad.objects.create(user_id=user)

        request_user = self.context["request"].user
        created_who = f"{request_user.first_name} {request_user.last_name}"

        models.History.objects.create(
            content_object=sklad,
            action="sklad_created",
            user_id=user,
            created_who=created_who,
            created_by=f"{user.first_name} {user.last_name}",
            reason="Omborxona qo'shildi",
            avatar=user.avatar if user.avatar else None,
        )

        return user

    def get_sklad_id(self, obj):
        sklad = models.Sklad.objects.filter(user_id=obj.id).first()
        return sklad.id if sklad else None


class SkladListSerializer(serializers.ModelSerializer):
    avatar = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "id",
            "first_name",
            "last_name",
            "phone",
            "username",
            "avatar",
            "role",
            "avatar",
        )

    def get_avatar(self, obj):
        return obj.avatar.url if obj.avatar else None
