import logging

from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import UserProfile
from .utils import generate_qr_code_for_user
from .emails import send_email_verification

logger = logging.getLogger(__name__)


@receiver(post_save, sender=UserProfile)
def handle_new_user_registration(sender, instance, created, **kwargs):
    """
    After a new user is created:
    1. Generate QR code
    2. Send email verification link
    """
    if created and not instance.is_superuser:
        try:
            # Generate QR code
            qr_file = generate_qr_code_for_user(instance)
            instance.qr_code.save(qr_file.name, qr_file, save=True)

            # Send verification email
            send_email_verification(instance)
            logger.info(f"Verification email sent to {instance.email}")
        except Exception as e:
            logger.error(f"Error during post-registration for {instance.email}: {e}")
