"""
Remove Shopify orders and clear local shopify_order_id so orders can be re-imported.

Usage:
  python manage.py unsync_shopify_orders ZH4AEZK6 KMV92LT7
  python manage.py unsync_shopify_orders --file order_ids.txt
  python manage.py unsync_shopify_orders KMV92LT7 --dry-run
"""
from django.core.management.base import BaseCommand, CommandError

from orders.models import Order
from products.services import ShopifyService


class Command(BaseCommand):
    help = (
        "Delete Shopify orders and clear local shopify_order_id for re-sync. "
        "Digistore order rows are kept."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "digistore_order_ids",
            nargs="*",
            help="Digistore order id(s) to unsync.",
        )
        parser.add_argument(
            "--file",
            type=str,
            default="",
            help="Text file with one Digistore order id per line.",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Report actions without deleting Shopify orders or updating DB.",
        )

    def handle(self, *args, **options):
        ids: list[str] = [x.strip() for x in options.get("digistore_order_ids") or [] if x.strip()]
        file_path = (options.get("file") or "").strip()
        if file_path:
            try:
                with open(file_path, encoding="utf-8") as fh:
                    ids.extend(line.strip() for line in fh if line.strip())
            except OSError as exc:
                raise CommandError(f"Could not read {file_path}: {exc}") from exc

        if not ids:
            raise CommandError("Provide digistore order id(s) or --file.")

        dry_run = bool(options.get("dry_run"))
        deleted = 0
        cleared = 0
        skipped = 0
        failed = 0

        for oid in ids:
            order = Order.objects.filter(digistore_order_id=oid).order_by("pk").first()
            if not order:
                self.stderr.write(self.style.ERROR(f"  {oid} not found in DB"))
                failed += 1
                continue

            shopify_id = (order.shopify_order_id or "").strip()
            if not shopify_id:
                self.stdout.write(f"  {oid} already unsynced (no shopify_order_id)")
                skipped += 1
                continue

            if dry_run:
                self.stdout.write(
                    f"  {oid} would delete Shopify order {shopify_id} and clear local link"
                )
                continue

            try:
                ShopifyService.delete_shopify_order(shopify_id)
                deleted += 1
            except Exception as exc:
                msg = str(exc)
                if "NOT_FOUND" in msg or "does not exist" in msg.lower():
                    self.stdout.write(
                        self.style.WARNING(
                            f"  {oid} Shopify order {shopify_id} already gone; clearing local link"
                        )
                    )
                else:
                    self.stderr.write(
                        self.style.ERROR(f"  {oid} Shopify delete failed: {exc}")
                    )
                    failed += 1
                    continue

            order.shopify_order_id = None
            order.sync_error = ""
            order.save(update_fields=["shopify_order_id", "sync_error", "updated_at"])
            cleared += 1
            self.stdout.write(
                self.style.SUCCESS(
                    f"  {oid} -> removed Shopify {shopify_id}, ready to resync"
                )
            )

        self.stdout.write(
            f"\nDeleted: {deleted}\n"
            f"Cleared: {cleared}\n"
            f"Skipped: {skipped}\n"
            f"Failed: {failed}\n"
        )
        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN — no changes made"))
