from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

from apps.chat.keygen import ensure_userkey
from apps.chat.models import UserKey


class Command(BaseCommand):
    help = 'Provision server-side X25519 keypairs for users without one.'

    def handle(self, *args, **options):
        User = get_user_model()
        users_without_key = User.objects.exclude(
            id__in=UserKey.objects.values_list('user_id', flat=True),
        )
        total = users_without_key.count()
        if total == 0:
            self.stdout.write(self.style.SUCCESS('All users already have keys.'))
            return
        created = 0
        for user in users_without_key.iterator():
            ensure_userkey(user)
            created += 1
        self.stdout.write(self.style.SUCCESS(
            f'Provisioned {created} keypair(s). Private keys are held in escrow '
            'until each user first logs in and claims them.'
        ))
