"""
Django signals for platform admin operations.
"""
import logging
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger(__name__)


@receiver(post_save, sender='platform_admin.SubscriptionPlan')
def subscription_plan_updated(sender, instance, created, **kwargs):
    """
    When a SubscriptionPlan is updated (not created), trigger a Celery task
    to sync the plan's permissions and limits to all tenants using that plan.
    """
    if created:
        # New plan, no tenants to update yet
        return

    # Import here to avoid circular imports
    from .tasks import sync_subscription_plan_to_tenants

    logger.info(f"SubscriptionPlan '{instance.name}' (ID: {instance.id}) was updated, "
                f"queuing sync task for all tenants on this plan")

    # Queue the task to run asynchronously
    sync_subscription_plan_to_tenants.delay(instance.id)
