from django_cloudflareimages_toolkit.models import CloudflareImage
from rest_framework import serializers

from apps.accounts.serializers import UserSerializer
from apps.media.serializers import CloudflareImageSerializer

from .models import Post, Tag


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ["id", "name", "slug"]


class PostListSerializer(serializers.ModelSerializer):
    """Lighter serializer for lists"""

    author = UserSerializer(read_only=True)
    tags = TagSerializer(many=True, read_only=True)
    image = CloudflareImageSerializer(read_only=True)

    class Meta:
        model = Post
        fields = [
            "id",
            "title",
            "slug",
            "excerpt",
            "image",
            "author",
            "published_at",
            "tags",
        ]


class PostDetailSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    tags = TagSerializer(many=True, read_only=True)
    image = CloudflareImageSerializer(read_only=True)
    image_id = serializers.PrimaryKeyRelatedField(
        queryset=CloudflareImage.objects.all(), source="image", write_only=True, required=False, allow_null=True
    )

    class Meta:
        model = Post
        fields = [
            "id",
            "title",
            "slug",
            "content",
            "excerpt",
            "image",
            "image_id",
            "author",
            "published_at",
            "is_published",
            "tags",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "slug", "created_at", "updated_at", "author"]
