"""
PX Sources signals - Auto-create SourceUsage records
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.contenttypes.models import ContentType


@receiver(post_save, sender='complaints.Complaint')
@receiver(post_save, sender='complaints.Inquiry')
def create_source_usage(sender, instance, created, **kwargs):
    """
    Auto-create SourceUsage when Complaint/Inquiry has a source.
    
    This ensures all feedback from PX sources is tracked for analytics.
    """
    if created and hasattr(instance, 'source') and instance.source_id:
        # Get content type for the instance
        content_type = ContentType.objects.get_for_model(instance)
        
        # Create or get the SourceUsage record
        from .models import SourceUsage
        SourceUsage.objects.get_or_create(
            source_id=instance.source_id,
            content_type=content_type,
            object_id=instance.id,
            defaults={
                'hospital_id': getattr(instance, 'hospital_id', None),
                'user_id': getattr(instance, 'created_by_id', None),
            }
        )
        
        # Update cached stats on the source
        if hasattr(instance.source, 'update_usage_stats'):
            # Use transaction.on_commit to update stats after transaction completes
            from django.db import transaction
            transaction.on_commit(lambda: instance.source.update_usage_stats())
