# hospit/tenant/signals.py

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from wagtail.models import Site

from .models import TenantProfile

CACHE_KEY_PREFIX = "tenant_profile_v1"


def _cache_key_for_site(site):
    return f"{CACHE_KEY_PREFIX}:site:{site.id}:{site.hostname}"


@receiver(post_save, sender=TenantProfile)
def clear_tenant_cache_on_save(sender, instance, **kwargs):
    """
    Jika TenantProfile berubah, hapus cache tenant terkait.
    """
    for site in Site.objects.all():
        try:
            profile = TenantProfile.for_site(site)
        except TenantProfile.DoesNotExist:
            continue

        if profile.pk == instance.pk:
            cache.delete(_cache_key_for_site(site))


@receiver(post_delete, sender=TenantProfile)
def clear_tenant_cache_on_delete(sender, instance, **kwargs):
    """
    Jika TenantProfile dihapus, hapus semua cache tenant profile.
    """
    for site in Site.objects.all():
        cache.delete(_cache_key_for_site(site))