from django.core.management.base import BaseCommand
from django.db import transaction
from apps.banking.models import Account


class Command(BaseCommand):
    help = "Met à jour les comptes existants pour ajouter des numéros de comptes manquants."

    @transaction.atomic
    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS("--- Mise à jour des numéros de comptes ---")
        )

        # Récupérer tous les comptes sans numéro de compte
        accounts_without_number = Account.objects.filter(
            account_number__isnull=True
        ) | Account.objects.filter(account_number="")

        if not accounts_without_number.exists():
            self.stdout.write(
                self.style.SUCCESS("✅ Tous les comptes ont déjà un numéro de compte.")
            )
            return

        updated_count = 0
        
        for account in accounts_without_number:
            old_number = account.account_number or "Aucun"
            
            # La méthode save() va automatiquement générer un numéro
            account.save()
            
            updated_count += 1
            self.stdout.write(
                self.style.SUCCESS(
                    f"✓ {account.name}: {old_number} → {account.account_number}"
                )
            )

        self.stdout.write(
            self.style.SUCCESS(
                f"--- {updated_count} compte(s) mis à jour ---"
            )
        )
