from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.text import slugify
from .models import MenuItem,Services

@receiver(pre_save, sender=MenuItem)
def auto_fill_menuitem_title_slug(sender, instance, **kwargs):
    # Set title if empty
    if not instance.title:
        if instance.service:
            instance.title = instance.service.title
        elif instance.document:
            instance.title = instance.document.title
        elif instance.page:
            instance.title = instance.page.title

    # Set slug if empty
    if not instance.slug and instance.title:
        instance.slug = slugify(instance.title)


# @receiver(pre_save, sender=Services)
# def unique_slug_for_services(sender, instance, **kwargs):
#     if not instance.slug and instance.title:
#         base_slug = slugify(instance.title)
#         slug = base_slug
#         counter = 1

#         # Ensure slug is unique
#         while Services.objects.filter(slug=slug).exclude(pk=instance.pk).exists():
#             slug = f"{base_slug}-{counter}"
#             counter += 1

#         instance.slug = slug
