from rest_framework import serializers

from apps.accounts.serializers import UserSerializer

from .models import ListItem, UserList


class ListItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = ListItem
        fields = [
            "id",
            "user_list",
            "content_type",
            "object_id",
            "rank",
            "notes",
            "created_at",
            "updated_at",
            "content_object_data",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]

    content_object_data = serializers.SerializerMethodField()

    def get_content_object_data(self, obj):
        """
        Return serialized data for the content object (Park or Ride).
        """
        # Avoid circular imports
        from apps.api.v1.parks.serializers import ParkListSerializer
        from apps.api.v1.rides.serializers import RideListSerializer
        from apps.parks.models import Park
        from apps.rides.models import Ride

        if isinstance(obj.content_object, Park):
            return ParkListSerializer(obj.content_object, context=self.context).data
        elif isinstance(obj.content_object, Ride):
            return RideListSerializer(obj.content_object, context=self.context).data
        return None


class UserListSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    items = ListItemSerializer(many=True, read_only=True)

    class Meta:
        model = UserList
        fields = [
            "id",
            "user",
            "title",
            "category",
            "description",
            "is_public",
            "items",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "user", "created_at", "updated_at"]
