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

from portfolio.models import Category, Portfolio

CATEGORY_LIST_CACHE_KEY = 'portfolio:category_list'
PORTFOLIO_LIST_CACHE_KEY = 'portfolio:portfolio_list'


def clear_category_cache(slug=None):
    cache.delete(CATEGORY_LIST_CACHE_KEY)
    if slug:
        cache.delete(f"portfolio:category_detail:{slug}")


def clear_portfolio_cache(pk=None):
    cache.delete(PORTFOLIO_LIST_CACHE_KEY)
    if pk:
        cache.delete(f"portfolio:portfolio_detail:{pk}")


@receiver(post_save, sender=Category)
@receiver(post_delete, sender=Category)
def clear_category_cache_on_change(sender, instance, **kwargs):
    clear_category_cache(slug=instance.slug)


@receiver(post_save, sender=Portfolio)
@receiver(post_delete, sender=Portfolio)
def clear_portfolio_cache_on_change(sender, instance, **kwargs):
    clear_portfolio_cache(pk=instance.pk)


@receiver(m2m_changed, sender=Portfolio.categories.through)
def clear_portfolio_cache_on_category_change(sender, instance, action, **kwargs):
    if action in {"post_add", "post_remove", "post_clear"}:
        clear_portfolio_cache(pk=instance.pk)
