from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import Registration
from .views import send_registration_email
import logging

logger = logging.getLogger(__name__)

@receiver(pre_save, sender=Registration)
def handle_registration_status_change(sender, instance, **kwargs):
    """
    Signal handler to send email when registration status is changed to approved
    """
    if not instance.pk:
        # This is a new registration, skip signal processing
        # (email is sent directly in views)
        return
        
    try:
        # Get the current state from the database
        current_instance = Registration.objects.get(pk=instance.pk)
        
        # Check if status is being changed to 'approved'
        status_changed_to_approved = (
            current_instance.status != 'approved' and 
            instance.status == 'approved'
        )
        
        # Check if payment_status is being changed to 'approved'
        payment_status_changed_to_approved = (
            current_instance.payment_status != 'approved' and 
            instance.payment_status == 'approved'
        )
        
        # If either status changed to approved, send email
        if status_changed_to_approved or payment_status_changed_to_approved:
            # Check if payment is pending
            payment_pending = instance.payment_status == 'pending'
            
            # Send email notification
            logger.info(f"Sending approval email to {instance.email} for registration {instance.registration_code}")
            send_registration_email(instance, payment_pending=payment_pending)
            logger.info(f"Email sent successfully to {instance.email}")
    
    except Registration.DoesNotExist:
        # This shouldn't happen normally
        pass
    except Exception as e:
        logger.error(f"Error sending registration email: {str(e)}")
