"""
Attribute existing tenants to the person who actually set them up.

The created_by field was added after these tenants existed, so nothing recorded
who created them. This assigns every unattributed tenant to a chosen user,
which is honest as long as that user really did create them.

Only tenants created before the moment this runs are touched, and only those
with no creator recorded, so anything added afterwards keeps its real value.

    python manage.py backfill_tenant_creator --user medmostaf@gmail.com
    python manage.py backfill_tenant_creator --user medmostaf@gmail.com --dry-run
    python manage.py backfill_tenant_creator            # picks the sole super admin
"""
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from apps.tenants.models import Tenant

User = get_user_model()


class Command(BaseCommand):
    help = 'Set created_by on tenants that have none.'

    def add_arguments(self, parser):
        parser.add_argument('--user', default=None,
                            help='Email or username of the creator to record.')
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **options):
        ident = options['user']

        if ident:
            user = User.objects.filter(email__iexact=ident).first() \
                or User.objects.filter(username__iexact=ident).first()
            if not user:
                raise CommandError(f'No user found matching "{ident}".')
        else:
            supers = list(User.objects.filter(role=User.ROLE_SUPER_ADMIN))
            if len(supers) != 1:
                raise CommandError(
                    f'Found {len(supers)} super admins, so the creator is ambiguous. '
                    'Pass --user with an email or username.'
                )
            user = supers[0]

        cutoff = timezone.now()
        qs = Tenant.objects.filter(created_by__isnull=True, created_at__lt=cutoff).order_by('id')
        rows = list(qs)

        if not rows:
            self.stdout.write('Nothing to do. Every tenant already has a creator recorded.')
            return

        label = user.get_full_name() or user.username
        self.stdout.write(f'Attributing {len(rows)} tenant(s) to {label}:')
        for t in rows:
            when = timezone.localtime(t.created_at).strftime('%d %b %Y, %H:%M')
            self.stdout.write(f'  {t.id:>3}  {t.name:<22} created {when}')

        if options['dry_run']:
            self.stdout.write(self.style.WARNING('Dry run, nothing saved.'))
            return

        updated = qs.update(created_by=user)
        self.stdout.write(self.style.SUCCESS(
            f'Done. {updated} tenant(s) now recorded as added by {label}.'
        ))
