# subscriptions/signals.py
"""
Signals: keep Company in sync with Subscription changes.
"""
from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import Subscription


@receiver(post_save, sender=Subscription)
def sync_company_on_subscription_change(sender, instance: Subscription, created, **kwargs):
    """
    When a subscription is saved and is_active=True,
    sync company.plan and company.expiry_date automatically.
    """
    if instance.is_active:
        company = instance.company
        changed = []
        if company.plan_id != instance.plan_id:
            company.plan = instance.plan
            changed.append('plan')
        if company.expiry_date != instance.expiry_date:
            company.expiry_date = instance.expiry_date
            changed.append('expiry_date')
        if changed:
            company.save(update_fields=changed)
