from rest_framework import serializers

from .models import Product, ProductImage, ProductSellingPoint


class ProductImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = ["id", "asset", "sort_order", "is_primary"]


class ProductSellingPointSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductSellingPoint
        fields = ["id", "title", "detail", "sort_order"]


class ProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, required=False)
    selling_points = ProductSellingPointSerializer(many=True, required=False)

    class Meta:
        model = Product
        fields = [
            "id",
            "title",
            "brand",
            "category",
            "target_audience",
            "specs",
            "description",
            "status",
            "cover_asset",
            "images",
            "selling_points",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]

    def create(self, validated_data):
        images = validated_data.pop("images", [])
        selling_points = validated_data.pop("selling_points", [])
        product = Product.objects.create(**validated_data)
        self._sync_children(product, images, selling_points)
        return product

    def update(self, instance, validated_data):
        images = validated_data.pop("images", None)
        selling_points = validated_data.pop("selling_points", None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        self._sync_children(instance, images, selling_points)
        return instance

    def _sync_children(self, product, images, selling_points):
        if images is not None:
            product.images.all().delete()
            for item in images:
                ProductImage.objects.create(product=product, **item)
        if selling_points is not None:
            product.selling_points.all().delete()
            for item in selling_points:
                ProductSellingPoint.objects.create(product=product, **item)
