from rest_framework import serializers
from api.models import Card, Collection


class CardSerializer(serializers.ModelSerializer):
    image_url = serializers.SerializerMethodField()
    collection_name = serializers.CharField(write_only=True, required=False)
    collection = serializers.PrimaryKeyRelatedField(
        queryset=Collection.objects.all(), required=False
    )

    class Meta:
        model = Card
        fields = ["id", "name", "collection", "collection_name", "image", "image_url"]

    def create(self, validated_data):
        collection_name = validated_data.pop("collection_name", None)
        if collection_name:
            collection, _ = Collection.objects.get_or_create(name=collection_name)
            validated_data["collection"] = collection
        elif not validated_data.get("collection"):
            raise serializers.ValidationError(
                {
                    "collection": "This field is required if collection_name is not provided."
                }
            )
        return super().create(validated_data)

    def get_image_url(self, obj):
        request = self.context.get("request")
        if obj.image:
            url = obj.image.url
            if request is not None:
                return request.build_absolute_uri(url)
            return url
        return None


class CollectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Collection
        fields = ["id", "name"]
