from rest_framework import serializers
from .models import Menu, MenuItem

class RecursiveField(serializers.Serializer):
    """Permet de sérialiser les enfants (sous-menus) indéfiniment."""
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

class MenuItemSerializer(serializers.ModelSerializer):
    url = serializers.ReadOnlyField() # Propriété calculée dans le modèle
    children = RecursiveField(many=True, read_only=True) # Les sous-menus

    class Meta:
        model = MenuItem
        fields = ['id', 'title', 'url', 'order', 'children']

class MenuSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()

    class Meta:
        model = Menu
        fields = ['slug', 'title', 'items']

    def get_items(self, obj):
        # On ne récupère que les items de premier niveau (ceux sans parent)
        # Les enfants seront chargés récursivement via le MenuItemSerializer
        qs = obj.items.filter(parent=None).order_by('order')
        return MenuItemSerializer(qs, many=True).data