from django.core.management.base import BaseCommand
from django.db import transaction

from apps.business.wallet.models import (
    ConversionRule,
    MonthlyConversionLog,
    SuperCoinTransaction,
    SuperCoinWallet,
    TDSLedger,
    TWMCoinGrant,
    UserVoucherCode,
    Wallet,
    WalletLedger,
)
from apps.business.withdrawals.models import BankAccount, BankAccountOTP, WithdrawalRequest


class Command(BaseCommand):
    help = "Delete all wallet and withdrawal data while preserving withdrawal deduction configs."

    def add_arguments(self, parser):
        parser.add_argument(
            "--confirm",
            action="store_true",
            help="Required safety flag to execute destructive deletion.",
        )

    def handle(self, *args, **options):
        if not options.get("confirm"):
            self.stdout.write(self.style.ERROR("Refusing to run without --confirm"))
            return

        with transaction.atomic():
            counts = {
                "WithdrawalRequest": WithdrawalRequest.objects.count(),
                "BankAccountOTP": BankAccountOTP.objects.count(),
                "BankAccount": BankAccount.objects.count(),
                "WalletLedger": WalletLedger.objects.count(),
                "SuperCoinTransaction": SuperCoinTransaction.objects.count(),
                "Wallet": Wallet.objects.count(),
                "SuperCoinWallet": SuperCoinWallet.objects.count(),
                "UserVoucherCode": UserVoucherCode.objects.count(),
                "TDSLedger": TDSLedger.objects.count(),
                "ConversionRule": ConversionRule.objects.count(),
                "MonthlyConversionLog": MonthlyConversionLog.objects.count(),
                "TWMCoinGrant": TWMCoinGrant.objects.count(),
            }

            self.stdout.write(self.style.WARNING("Purging wallet and withdrawal data:"))
            for name, count in counts.items():
                self.stdout.write(f"  {name}: {count}")

            WithdrawalRequest.objects.all().delete()
            BankAccountOTP.objects.all().delete()
            BankAccount.objects.all().delete()
            WalletLedger.objects.all().delete()
            SuperCoinTransaction.objects.all().delete()
            Wallet.objects.all().delete()
            SuperCoinWallet.objects.all().delete()
            UserVoucherCode.objects.all().delete()
            TDSLedger.objects.all().delete()
            ConversionRule.objects.all().delete()
            MonthlyConversionLog.objects.all().delete()
            TWMCoinGrant.objects.all().delete()

        self.stdout.write(self.style.SUCCESS("Wallet and withdrawal data deleted successfully; deduction configs preserved."))
