from django.core.management.base import BaseCommand
from django.db import transaction
from decimal import Decimal

from shop_management.models.data.stock_transfer import StockTransfer
from shop_management.models.data.sale import Sale
from shop_management.views.data.stock import StockTransferViewSet


class Command(BaseCommand):
    help = (
        "Create missing from-branch Sale rows for accepted stock transfers "
        "with Payment enabled. Also removes duplicate sales for the same transfer."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--shop",
            type=int,
            help="Only from-branch (supplier) shop id",
        )
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        shop_id = options.get("shop")
        dry_run = options["dry_run"]

        qs = (
            StockTransfer.objects.filter(
                status=StockTransfer.Status.ACCEPTED,
                show_payment_button=True,
            )
            .select_related(
                "product",
                "supplier_branch",
                "customer_branch",
                "currency",
                "source_stock",
                "source_stock__purchase_item",
                "created_by",
                "accepted_by",
            )
            .order_by("id")
        )
        if shop_id:
            qs = qs.filter(supplier_branch_id=shop_id)

        view = StockTransferViewSet()
        created = 0
        skipped = 0
        deduped = 0

        for transfer in qs:
            notes = view._transfer_sale_notes(transfer)
            sales = list(
                Sale.objects.filter(
                    shop_id=transfer.supplier_branch_id,
                    notes=notes,
                ).order_by("id")
            )
            if not sales:
                sales = list(
                    Sale.objects.filter(
                        shop_id=transfer.supplier_branch_id,
                        notes__icontains=transfer.transfer_id,
                    ).order_by("id")
                )

            if len(sales) > 1:
                keep, extras = sales[0], sales[1:]
                self.stdout.write(
                    f"Dedupe {transfer.transfer_id}: keep sale #{keep.id}, "
                    f"remove {[s.id for s in extras]}"
                )
                deduped += len(extras)
                if not dry_run:
                    with transaction.atomic():
                        for sale in extras:
                            sale.sale_items.all().delete()
                            sale.delete()
                sales = [keep]

            if sales:
                skipped += 1
                continue

            amount = Decimal(str(transfer.transfer_quantity or 0)) * Decimal(
                str(transfer.sale_price or 0)
            )
            self.stdout.write(
                f"Transfer {transfer.transfer_id}: "
                f"{transfer.supplier_branch.name} -> {transfer.customer_branch.name} "
                f"qty={transfer.transfer_quantity} amount={amount}"
            )
            created += 1
            if dry_run:
                continue

            with transaction.atomic():
                view._ensure_transfer_sale(
                    transfer,
                    source_stock=transfer.source_stock,
                    user=transfer.accepted_by or transfer.created_by,
                )

        action = "Would create" if dry_run else "Created"
        self.stdout.write(
            self.style.SUCCESS(
                f"{action} {created} sale(s); skipped {skipped} already present; "
                f"removed {deduped} duplicate sale(s)."
            )
        )
