"""
Django signals for automatically updating statistics cache.

This module contains signal handlers that invalidate the stats cache
whenever relevant entities are created, updated, or deleted.
"""

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

from apps.parks.models import Company as ParkCompany
from apps.parks.models import Park, ParkPhoto, ParkReview
from apps.rides.models import (
    Company as RideCompany,
)
from apps.rides.models import (
    Ride,
    RidePhoto,
    RideReview,
    RollerCoasterStats,
)


def invalidate_stats_cache():
    """
    Invalidate the platform stats cache.

    This function is called whenever any entity that affects statistics
    is created, updated, or deleted.
    """
    cache.delete("platform_stats")
    # Also update the timestamp for when stats were last invalidated
    from datetime import datetime

    cache.set("platform_stats_timestamp", datetime.now().isoformat(), 300)


# Park signals
@receiver(post_save, sender=Park)
@receiver(post_delete, sender=Park)
def park_changed(sender, **kwargs):
    """Handle Park creation/deletion."""
    invalidate_stats_cache()


# Ride signals
@receiver(post_save, sender=Ride)
@receiver(post_delete, sender=Ride)
def ride_changed(sender, **kwargs):
    """Handle Ride creation/deletion."""
    invalidate_stats_cache()


# Roller coaster stats signals
@receiver(post_save, sender=RollerCoasterStats)
@receiver(post_delete, sender=RollerCoasterStats)
def roller_coaster_stats_changed(sender, **kwargs):
    """Handle RollerCoasterStats creation/deletion."""
    invalidate_stats_cache()


# Company signals (both park and ride companies)
@receiver(post_save, sender=ParkCompany)
@receiver(post_delete, sender=ParkCompany)
def park_company_changed(sender, **kwargs):
    """Handle ParkCompany creation/deletion."""
    invalidate_stats_cache()


@receiver(post_save, sender=RideCompany)
@receiver(post_delete, sender=RideCompany)
def ride_company_changed(sender, **kwargs):
    """Handle RideCompany creation/deletion."""
    invalidate_stats_cache()


# Photo signals
@receiver(post_save, sender=ParkPhoto)
@receiver(post_delete, sender=ParkPhoto)
def park_photo_changed(sender, **kwargs):
    """Handle ParkPhoto creation/deletion."""
    invalidate_stats_cache()


@receiver(post_save, sender=RidePhoto)
@receiver(post_delete, sender=RidePhoto)
def ride_photo_changed(sender, **kwargs):
    """Handle RidePhoto creation/deletion."""
    invalidate_stats_cache()


# Review signals
@receiver(post_save, sender=ParkReview)
@receiver(post_delete, sender=ParkReview)
def park_review_changed(sender, **kwargs):
    """Handle ParkReview creation/deletion."""
    invalidate_stats_cache()


@receiver(post_save, sender=RideReview)
@receiver(post_delete, sender=RideReview)
def ride_review_changed(sender, **kwargs):
    """Handle RideReview creation/deletion."""
    invalidate_stats_cache()
