from rest_framework import serializers

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


class MarketLocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Location
        fields = ("label", "long", "lat")


class MarketUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            "id",
            "first_name",
            "last_name",
            "phone",
            "password",
            "role",
            "avatar",
        )


class AddMarketSerializer(serializers.ModelSerializer):
    user_id = MarketUserSerializer()
    location_id = MarketLocationSerializer()

    class Meta:
        model = models.Market
        fields = (
            "name",
            "company_name",
            "avatar",
            "phone",
            "user_id",
            "location_id",
        )

    def create(self, validated_data):
        user_data = validated_data.pop("user_id")
        location_data = validated_data.pop("location_id")
        password = user_data.pop("password", None)
        user_data.pop("role", None)  # remove 'role' from user_data

        user = User.objects.create(role="market", **user_data)
        if password:
            user.set_password(password)
            user.save()

        location = models.Location.objects.create(**location_data)

        market = models.Market.objects.create(
            user_id=user, location_id=location, **validated_data
        )

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

        models.History.objects.create(
            content_object=market,
            action="market_created",
            user_id=user,
            created_who=created_who,
            created_by=market.company_name,
            reason="Market qo'shildi",
            avatar=market.avatar if market.avatar else None,
        )

        return market
