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

from .keygen import ensure_userkey
from .models import ConversationParticipant


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_chat_key_for_new_user(sender, instance, created, **kwargs):
    """Auto-provision a chat keypair so every new user is reachable.

    Server briefly holds the private key in escrow until the user first
    logs in and claims it.
    """
    if created:
        ensure_userkey(instance)


@receiver(post_save, sender=ConversationParticipant)
def ensure_key_for_participant(sender, instance, created, **kwargs):
    """Guarantee any user added to a conversation has a chat key.

    Without this, send() would 400 with 'Missing key wraps' if a participant
    had been created before the chat feature shipped and somehow slipped
    past the backfill.
    """
    if created:
        ensure_userkey(instance.user)
