from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from apps.accounts.models import Account, AccountRole


class Command(BaseCommand):
    help = 'Assigns the single super admin role to an existing account.'

    def add_arguments(self, parser):
        parser.add_argument('email')

    @transaction.atomic
    def handle(self, *args, **options):
        email = Account.objects.normalize_email(options['email'])
        account = Account.objects.select_for_update().filter(email__iexact=email).first()
        if account is None:
            raise CommandError('No account exists with that email.')

        current = (
            Account.objects.select_for_update()
            .filter(role=AccountRole.SUPER_ADMIN)
            .exclude(pk=account.pk)
            .first()
        )
        if current is not None:
            raise CommandError('A different super admin is already active.')

        account.role = AccountRole.SUPER_ADMIN
        account.is_active = True
        account.is_staff = True
        account.is_superuser = True
        account.save(
            update_fields=['role', 'is_active', 'is_staff', 'is_superuser', 'updated_at']
        )
        self.stdout.write(self.style.SUCCESS('Super admin assigned.'))
