from django.core import exceptions
from rest_framework import serializers

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


class AddCourierSerializer(serializers.ModelSerializer):
    courier_id = serializers.SerializerMethodField()

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

    def create(self, validated_data):
        validated_data["role"] = "courier"
        user = User.objects.create_user(**validated_data)
        courier = models.Courier.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=courier,
            action="courier_created",
            created_who=created_who,
            user_id=user,
            created_by=f"{user.first_name} {user.last_name}",
            reason="Kuryer qo'shildi",
            avatar=user.avatar if user.avatar else None,
        )

        return user

    def get_courier_id(self, obj):
        courier = models.Courier.objects.filter(user_id=obj.id).first()
        return courier.id if courier else None


class CouriersListSerializer(serializers.ModelSerializer):
    courier_history = serializers.SerializerMethodField()
    avatar = serializers.SerializerMethodField()

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

    def get_courier_history(self, obj):
        try:
            user = User.objects.get(id=obj.id, role="courier")
            courier = models.Courier.objects.get(user_id=user.id)
            courier_history = models.CourierHistory.objects.filter(
                courier_id=courier.id
            )  # noqa
            return CourierHistorySerializer(courier_history, many=True).data
        except exceptions.ObjectDoesNotExist:
            return []

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