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


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def sync_dm_chat_identity(sender, instance, created, update_fields, **kwargs):
    """Keep DM chat name/icon in sync when a user updates their username or avatar."""
    if created:
        return

    changed = set(update_fields) if update_fields else None  # None = full save
    username_changed = changed is None or 'username' in changed
    avatar_changed = changed is None or 'avatar' in changed

    if not (username_changed or avatar_changed):
        return

    from .models import Chat

    dm_chats = Chat.objects.filter(
        chat_type=Chat.ChatType.DM,
        members=instance,
    ).exclude(owner=instance)

    if not dm_chats.exists():
        return

    update_kwargs = {}
    if username_changed:
        update_kwargs['name'] = instance.username
    if avatar_changed:
        update_kwargs['icon'] = instance.avatar.name if instance.avatar else None

    dm_chats.update(**update_kwargs)
