from django.utils.html import format_html
from django.urls import reverse


def get_used_in_posts_html(image):
    """Retourne le HTML des posts qui utilisent cette image"""
    from posts.models import Post
    posts_using_image = Post.objects.filter(images=image)
    if posts_using_image.exists():
        post_links = []
        for post in posts_using_image[:3]:  # Limiter à 3 posts
            post_links.append(
                format_html('<a href="{}">{}</a>',
                    reverse('admin:posts_post_change', args=[post.id]),
                    post.content[:30] + '...' if len(post.content) > 30 else post.content
                )
            )
        if posts_using_image.count() > 3:
            post_links.append(f"... et {posts_using_image.count() - 3} autres")
        return format_html(", ".join(post_links))
    return "Non utilisé"