# home/api/cache_invalidation.py

from django.core.cache import cache
from wagtail.models import Site
from wagtail.signals import page_published, page_unpublished

# Samakan prefix dengan yang dipakai di API
PAGES_PREFIX = "pages_api_v1"
ARTICLES_PREFIX = "articles_api_v1"


def _clear_site_cache(site):
    """
    Hapus cache pages & articles untuk satu Site (tenant).
    """
    patterns = [
        f"{PAGES_PREFIX}:*site:{site.id}:{site.hostname}",
        f"{ARTICLES_PREFIX}:*site:{site.id}:{site.hostname}",
    ]

    # Django cache default tidak support delete by pattern
    # Jika pakai Redis, gunakan delete_pattern
    backend = cache
    for pattern in patterns:
        try:
            backend.delete_pattern(pattern)
        except Exception:
            # Fallback: no-op untuk backend yang tidak support pattern
            pass


@page_published.connect
def invalidate_cache_on_publish(sender, **kwargs):
    page = kwargs.get("instance")
    if not page:
        return

    # Cari site yang menaungi page ini
    for site in Site.objects.all():
        if page.is_descendant_of(site.root_page):
            _clear_site_cache(site)


@page_unpublished.connect
def invalidate_cache_on_unpublish(sender, **kwargs):
    page = kwargs.get("instance")
    if not page:
        return

    for site in Site.objects.all():
        if page.is_descendant_of(site.root_page):
            _clear_site_cache(site)