"""
One-off ops script: bulk-move all stock currently sitting in the Online
Store (Website) location (WEBSITE) into the Main Warehouse (MAIN-WH).

Goes straight through inventory_service.transfer_stock() per book — i.e.
auto-transferred and auto-approved, bypassing the normal
PendingInventoryTransaction maker-checker queue entirely. Only intended for
this one-off consolidation; day-to-day transfers should still go through
the "Transfer Stock" admin form, which goes through approval.

Each transfer is its own InventoryTransaction (type=transfer), so it counts
as "received" on the Stock Received report for any book that had no prior
receipt_from_author record on file.

Usage:
    python manage.py transfer_website_stock_to_main_wh --dry-run   # preview only
    python manage.py transfer_website_stock_to_main_wh             # commit
"""

from django.core.management.base import BaseCommand, CommandError

from inventory.models import InventoryBalance, StockLocation
from inventory.services.inventory_service import transfer_stock

SOURCE_CODE = "WEBSITE"
DEST_CODE = "MAIN-WH"


class Command(BaseCommand):
    help = (
        f"Bulk-transfer all available stock from {SOURCE_CODE} to {DEST_CODE}, "
        "auto-approved (bypasses the pending-transaction review queue)."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run", action="store_true",
            help="Print what would be transferred without saving anything.",
        )

    def handle(self, *args, **options):
        dry_run = options["dry_run"]

        try:
            source = StockLocation.objects.get(code=SOURCE_CODE)
            destination = StockLocation.objects.get(code=DEST_CODE)
        except StockLocation.DoesNotExist as exc:
            raise CommandError(f"Location not found: {exc}")

        balances = (
            InventoryBalance.objects
            .filter(location=source, quantity_on_hand__gt=0)
            .select_related("book")
            .order_by("book__title")
        )

        transferred = []
        skipped = []
        failed = []
        for balance in balances:
            qty = balance.quantity_available
            if qty <= 0:
                skipped.append((balance.book, balance.quantity_on_hand, balance.quantity_reserved))
                continue

            self.stdout.write(f"  {balance.book.title} (id={balance.book_id}): {qty} -> {DEST_CODE}")
            if not dry_run:
                try:
                    transfer_stock(
                        book=balance.book,
                        source=source,
                        destination=destination,
                        quantity=qty,
                        reference="Bulk WEBSITE -> MAIN-WH consolidation",
                        notes="Auto-transferred via transfer_website_stock_to_main_wh management command.",
                        user=None,
                    )
                except Exception as exc:
                    failed.append((balance.book, qty, str(exc)))
                    self.stdout.write(self.style.ERROR(f"    FAILED: {exc}"))
                    continue
            transferred.append((balance.book, qty))

        if skipped:
            self.stdout.write(self.style.WARNING(
                f"\nSkipped {len(skipped)} book(s) with no available stock (fully reserved):"
            ))
            for book, on_hand, reserved in skipped:
                self.stdout.write(f"  {book.title} (id={book.pk}): on_hand={on_hand}, reserved={reserved}")

        if failed:
            self.stdout.write(self.style.ERROR(f"\n{len(failed)} book(s) failed to transfer:"))
            for book, qty, err in failed:
                self.stdout.write(f"  {book.title} (id={book.pk}): {qty} units — {err}")

        total_units = sum(q for _, q in transferred)
        if dry_run:
            self.stdout.write(self.style.WARNING(
                f"\nDRY RUN — {len(transferred)} book(s), {total_units} total units, "
                f"would be transferred {SOURCE_CODE} -> {DEST_CODE}. Nothing was saved."
            ))
        else:
            self.stdout.write(self.style.SUCCESS(
                f"\nDone. Transferred {len(transferred)} book(s), {total_units} total units, "
                f"{SOURCE_CODE} -> {DEST_CODE}."
            ))
