from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from parks.models import Park
from rides.models import Ride
from .models import Company, Manufacturer

@receiver([post_save, post_delete], sender=Park)
def update_company_stats(sender, instance, **kwargs):
    """Update company statistics when a park is added, modified, or deleted."""
    if instance.owner:
        # Update total parks
        total_parks = Park.objects.filter(owner=instance.owner).count()
        total_rides = Ride.objects.filter(park__owner=instance.owner).count()
        
        Company.objects.filter(id=instance.owner.id).update(
            total_parks=total_parks,
            total_rides=total_rides
        )

@receiver([post_save, post_delete], sender=Ride)
def update_manufacturer_stats(sender, instance, **kwargs):
    """Update manufacturer statistics when a ride is added, modified, or deleted."""
    if instance.manufacturer:
        # Update total rides and roller coasters
        total_rides = Ride.objects.filter(manufacturer=instance.manufacturer).count()
        total_roller_coasters = Ride.objects.filter(
            manufacturer=instance.manufacturer,
            category='RC'
        ).count()
        
        Manufacturer.objects.filter(id=instance.manufacturer.id).update(
            total_rides=total_rides,
            total_roller_coasters=total_roller_coasters
        )

@receiver(post_save, sender=Ride)
def update_company_ride_stats(sender, instance, **kwargs):
    """Update company ride statistics when a ride is added or modified."""
    if instance.park and instance.park.owner:
        total_rides = Ride.objects.filter(park__owner=instance.park.owner).count()
        Company.objects.filter(id=instance.park.owner.id).update(total_rides=total_rides)
