from django_cloudflareimages_toolkit.models import CloudflareImage
from rest_framework import serializers

from apps.accounts.serializers import UserSerializer

from .models import Photo


# We need a serializer for the CloudflareImage model too if we want to show variants
class CloudflareImageSerializer(serializers.ModelSerializer):
    variants = serializers.JSONField(read_only=True)

    class Meta:
        model = CloudflareImage
        fields = ["id", "cloudflare_id", "variants"]


class PhotoSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    image = CloudflareImageSerializer(read_only=True)
    cloudflare_image_id = serializers.CharField(write_only=True)

    # Helper for frontend to get URLs easily
    url = serializers.SerializerMethodField()
    thumbnail = serializers.SerializerMethodField()

    class Meta:
        model = Photo
        fields = [
            "id",
            "user",
            "image",
            "cloudflare_image_id",
            "content_type",
            "object_id",
            "caption",
            "source",
            "is_public",
            "created_at",
            "updated_at",
            "url",
            "thumbnail",
        ]
        read_only_fields = ["id", "user", "created_at", "updated_at"]

    def create(self, validated_data):
        cloudflare_id = validated_data.pop("cloudflare_image_id", None)
        if cloudflare_id:
            # Get or create the CloudflareImage wrapper
            # We assume it exists on CF side. We just need the DB record.
            image, _ = CloudflareImage.objects.get_or_create(cloudflare_id=cloudflare_id)
            validated_data["image"] = image

        return super().create(validated_data)

    def get_url(self, obj):
        # Return public variant or default
        if obj.image:
            # Check if get_url method exists or we construct strictly
            return getattr(obj.image, "get_url", lambda x: None)("public")
        return None

    def get_thumbnail(self, obj):
        if obj.image:
            return getattr(obj.image, "get_url", lambda x: None)("thumbnail")
        return None
