from django.core.management.base import BaseCommand
from django.core.management import call_command


class Command(BaseCommand):
    help = (
        "Merge duplicate products + stock rows per branch. "
        "Prefer: python manage.py fix_branch_inventory --all"
    )

    def add_arguments(self, parser):
        parser.add_argument("--shop", type=int, help="Branch shop id")
        parser.add_argument(
            "--all",
            action="store_true",
            help="Run for every branch",
        )
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        shop = options.get("shop")
        dry_run = options["dry_run"]
        run_all = options["all"]
        if not shop and not run_all:
            self.stderr.write(self.style.ERROR("Use --shop=<id> or --all"))
            return

        kwargs = {"skip_sales": True, "dry_run": dry_run}
        if run_all:
            kwargs["all"] = True
        else:
            kwargs["shop"] = shop
        self.stdout.write(
            self.style.NOTICE(
                "Delegating to fix_branch_inventory (products + stock merge)..."
            )
        )
        call_command("fix_branch_inventory", **kwargs)
