# payments/management/commands/backfill_recharge_users.py
from django.core.management.base import BaseCommand
from django.db import transaction
from payments.models import RechargePaymentSummary  # adjust paths
from recharge.models import RechargeTransaction

class Command(BaseCommand):
    help = "Backfill RechargeTransaction.user from RechargePaymentSummary(user, order_id)"

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true", help="Do not write changes")

    def handle(self, *args, **opts):
        dry = opts["dry_run"]
        updated = 0
        missing = 0

        with transaction.atomic():
            qs = RechargeTransaction.objects.filter(user__isnull=True)
            for rt in qs.iterator():
                ps = RechargePaymentSummary.objects.filter(order_id=rt.order_id).only("user_id").first()
                if not ps or not ps.user_id:
                    missing += 1
                    continue
                rt.user_id = ps.user_id
                if not dry:
                    rt.save(update_fields=["user"])
                updated += 1

            if dry:
                transaction.set_rollback(True)

        self.stdout.write(self.style.SUCCESS(
            f"Updated: {updated}, Missing: {missing}, Dry-run: {dry}"
        ))
