from rest_framework import serializers

from .models import Guestbook, Memory


def _absolute_uri(request, path: str) -> str:
    if request is not None:
        return request.build_absolute_uri(path)
    return path


class MemorySerializer(serializers.ModelSerializer):
    """`image` 为首张 URL（兼容旧前端）；`images` 为主图 + 附加图完整列表。"""

    image = serializers.SerializerMethodField()
    images = serializers.SerializerMethodField()

    class Meta:
        model = Memory
        fields = (
            "id",
            "story_order",
            "date",
            "event_title",
            "main_text",
            "unique_feature_type",
            "nepal_art_style",
            "image",
            "images",
            "is_finale",
        )

    def get_images(self, obj: Memory) -> list[str]:
        request = self.context.get("request")
        out: list[str] = []
        if obj.image:
            out.append(_absolute_uri(request, obj.image.url))
        for p in obj.photos.all():
            out.append(_absolute_uri(request, p.image.url))
        return out

    def get_image(self, obj: Memory) -> str | None:
        imgs = self.get_images(obj)
        return imgs[0] if imgs else None


class GuestbookCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Guestbook
        fields = ("id", "nickname", "message", "created_at")
        read_only_fields = ("id", "created_at")
