"""
Fix transfer purchase lines that stored full stock qty instead of transfer qty.

Does NOT change Stock quantity. Only the Purchases page number.

Example:

  python manage.py repair_transfer_purchase_qty
  python manage.py repair_transfer_purchase_qty --apply
"""

from django.core.management.base import BaseCommand
from django.db import transaction

from shop_management.models.data.stock_transfer import StockTransfer


class Command(BaseCommand):
    help = (
        "Set Transfer/stock-only purchase item qty to the transfer qty. "
        "Does not change stock. Dry-run unless --apply."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--apply",
            action="store_true",
            help="Write purchase item qty. Without this flag, only print.",
        )
        parser.add_argument(
            "--product-name",
            type=str,
            help="Only this product name (optional).",
        )

    def handle(self, *args, **options):
        apply_changes = bool(options.get("apply"))
        product_name = (options.get("product_name") or "").strip()
        mode = "APPLY" if apply_changes else "DRY-RUN"
        self.stdout.write(
            self.style.MIGRATE_HEADING(
                f"{mode}: purchase line = transfer qty (stock qty not changed)"
            )
        )

        transfers = (
            StockTransfer.objects.filter(
                status=StockTransfer.Status.ACCEPTED,
                target_stock__isnull=False,
                target_stock__purchase_item__isnull=False,
            )
            .select_related(
                "product",
                "supplier_branch",
                "customer_branch",
                "target_stock__purchase_item",
                "target_stock__purchase_item__product",
                "target_stock__purchase_item__purchase",
            )
            .order_by("transfer_date", "id")
        )
        if product_name:
            transfers = transfers.filter(
                target_stock__purchase_item__product__name__iexact=product_name
            )

        updated = 0
        ok = 0
        for transfer in transfers:
            item = transfer.target_stock.purchase_item
            if not item:
                continue
            transfer_qty = int(transfer.transfer_quantity or 0)
            current = int(item.quantity or 0)
            name = getattr(getattr(item, "product", None), "name", None) or transfer.product
            if current == transfer_qty:
                ok += 1
                continue
            dest = transfer.customer_branch.name if transfer.customer_branch else "?"
            self.stdout.write(
                f"  {transfer.transfer_date} | {dest} | {name} | "
                f"purchase line {current} → {transfer_qty} "
                f"(stock stays {transfer.target_stock.quantity})"
            )
            if apply_changes:
                with transaction.atomic():
                    item.quantity = transfer_qty
                    item.save(update_fields=["quantity", "updated_at"])
            updated += 1

        self.stdout.write("")
        self.stdout.write(self.style.SUCCESS("Summary:"))
        self.stdout.write(f"  already correct: {ok}")
        self.stdout.write(
            f"  {'Updated' if apply_changes else 'Would update'} purchase lines: {updated}"
        )
        if not apply_changes and updated:
            self.stdout.write("")
            self.stdout.write(
                "If the list looks right, run:\n"
                "  python manage.py repair_transfer_purchase_qty --apply"
            )
