"""回填罚单 club_id（从关联订单或被罚用户）。"""
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.constants import CLUB_ID_DEFAULT
from jituan.services.club_penalty import resolve_penalty_club_id
from orders.models import Order, Penalty
from users.business_models import User


class Command(BaseCommand):
    help = '按关联订单/被罚用户回填 fadan.club_id（默认仅处理仍为 xq 的记录）'

    def add_arguments(self, parser):
        parser.add_argument('--all', action='store_true', help='重算全部罚单（慎用）')
        parser.add_argument('--dry-run', action='store_true')

    def handle(self, *args, **options):
        dry = options['dry_run']
        qs = Penalty.query.all()
        if not options['all']:
            qs = qs.filter(ClubID=CLUB_ID_DEFAULT)

        updated = 0
        with transaction.atomic():
            for p in qs.to_list():
                order = None
                if p.RelatedOrderID:
                    order = Order.query.filter(OrderID=p.RelatedOrderID).first()
                cid = resolve_penalty_club_id(
                    order=order,
                    penalized_user_id=p.PenalizedUserID,
                )
                if cid and cid != p.ClubID:
                    if dry:
                        self.stdout.write(f'would update penalty {p.id}: {p.ClubID} -> {cid}')
                    else:
                        p.ClubID = cid
                        p.save(update_fields=['ClubID'])
                    updated += 1

        self.stdout.write(self.style.SUCCESS(f'罚单 club_id 更新 {updated} 条'))
