from argparse import ArgumentParser
from typing import Any

from django.core.management.base import BaseCommand

from core.models import AttributeValue, Product, ProductImage


class Command(BaseCommand):
    help = "Delete Product rows with no OrderProduct, in batches"

    def add_arguments(self, parser: ArgumentParser):
        parser.add_argument(
            "-s",
            "--size",
            required=False,
            default=5000,
            help="Chunk size to delete",
        )

    def handle(self, *args: list[Any], **options: dict[Any, Any]) -> None:
        size: int = options["size"]  # type: ignore [assignment]
        while True:
            batch_ids = list(Product.objects.filter(orderproduct__isnull=True).values_list("pk", flat=True)[:size])
            if not batch_ids:
                break
            try:
                AttributeValue.objects.filter(product_id__in=batch_ids).delete()
                ProductImage.objects.filter(product_id__in=batch_ids).delete()
                Product.objects.filter(pk__in=batch_ids).delete()
            except Exception as e:
                self.stdout.write("Couldn't delete some of the products(will retry later): %s" % str(e))
                continue
            self.stdout.write(f"Deleted {len(batch_ids)} products…")

        self.stdout.write("✅ All unordered products removed.")
