# src/django_core_micha/auth/signals.py
from django.conf import settings
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from allauth.socialaccount.signals import pre_social_login
import logging

logger = logging.getLogger(__name__)

@receiver(pre_save, sender=settings.AUTH_USER_MODEL)
def prevent_password_wipe(sender, instance, **kwargs):
    # ... (Dein Code von vorhin: Password Wipe Prevention) ...
    if instance.pk:
        try:
            old_user = sender.objects.get(pk=instance.pk)
            has_old_pw = old_user.password and not old_user.password.startswith('!')
            is_wiping_pw = not instance.password or instance.password.startswith('!')

            if has_old_pw and is_wiping_pw:
                instance.password = old_user.password
                logger.info(f"Prevented password wipe for user {instance.email}")
        except sender.DoesNotExist:
            pass

@receiver(pre_social_login)
def force_auto_connect_on_email_match(sender, request, sociallogin, **kwargs):
    # ... (Dein Code von vorhin: Force Auto Connect) ...
    if sociallogin.is_existing or not sociallogin.email_addresses:
        return
    
    social_email = sociallogin.email_addresses[0].email
    User = get_user_model()

    try:
        user = User.objects.get(email__iexact=social_email)
        sociallogin.connect(request, user)
        logger.info(f"Auto-connected social account for {social_email}")
    except User.DoesNotExist:
        pass