from rest_framework import serializers
from .models import Gallery, OthergalleryImages


class OtherGalleryImageSerializer(serializers.ModelSerializer):
    other_shop_images = serializers.SerializerMethodField()

    class Meta:
        model = OthergalleryImages
        fields = ['id', 'other_shop_images']

    def get_other_shop_images(self, obj):
        request = self.context.get('request')
        if obj.other_shop_images and request:
            return request.build_absolute_uri(obj.other_shop_images.url)
        return obj.other_shop_images.url if obj.other_shop_images else None


class GalleryListSerializer(serializers.ModelSerializer):
    """Lightweight gallery serializer for masonry grids."""
    main_image = serializers.SerializerMethodField()
    url = serializers.SerializerMethodField()

    class Meta:
        model = Gallery
        fields = ['id', 'title', 'slug', 'main_image', 'active', 'url']

    def get_main_image(self, obj):
        request = self.context.get('request')
        if obj.main_image and request:
            return request.build_absolute_uri(obj.main_image.url)
        return obj.main_image.url if obj.main_image else None

    def get_url(self, obj):
        return f'/gallery/{obj.slug or obj.id}'


class GalleryDetailSerializer(GalleryListSerializer):
    """Gallery detail with all other images."""
    other_images = serializers.SerializerMethodField()

    class Meta(GalleryListSerializer.Meta):
        fields = GalleryListSerializer.Meta.fields + ['other_images']

    def get_other_images(self, obj):
        qs = obj.othergalleryimages_set.all()
        return OtherGalleryImageSerializer(qs, many=True, context=self.context).data