# from django.core.management.base import BaseCommand
# from vouchers.services import pull_voucher

# class Command(BaseCommand):
#     help = "Pull voucher using command"

#     def add_arguments(self, parser):
#         parser.add_argument('--brand', type=str, required=True)
#         parser.add_argument('--amount', type=int, required=True)
#         parser.add_argument('--qty', type=int, default=1)
#         parser.add_argument('--orderid', type=str, required=True)

#     def handle(self, *args, **options):
#         result = pull_voucher(
#             brand_product_code=options['brand'],
#             denomination=options['amount'],
#             quantity=options['qty'],
#             order_id=options['orderid']
#         )
#         self.stdout.write(str(result))

# management/commands/pull_voucher.py

from django.core.management.base import BaseCommand
from vouchers.services import pull_voucher
from vouchers.utils import generate_order_id  # Optional helper if you want to auto-generate order ID

class Command(BaseCommand):
    help = "🔄 Pull a voucher using API and log it to database."

    def add_arguments(self, parser):
        parser.add_argument('--brand', type=str, required=True, help='Brand Product Code')
        parser.add_argument('--amount', type=int, required=True, help='Denomination amount')
        parser.add_argument('--qty', type=int, default=1, help='Quantity (default: 1)')
        parser.add_argument('--orderid', type=str, help='External Order ID (optional)')

    def handle(self, *args, **options):
        brand = options['brand']
        amount = options['amount']
        qty = options['qty']
        order_id = options['orderid'] or generate_order_id(prefix="ORDER_CLI")

        self.stdout.write(self.style.NOTICE(f"📦 Pulling {qty} voucher(s) for brand: {brand}, ₹{amount}"))
        self.stdout.write(self.style.NOTICE(f"🆔 Order ID: {order_id}"))

        result = pull_voucher(
            brand_product_code=brand,
            denomination=amount,
            quantity=qty,
            order_id=order_id
        )

        if result.get("success"):
            self.stdout.write(self.style.SUCCESS("✅ Voucher pulled successfully!"))
            self.stdout.write(self.style.SUCCESS(str(result.get("data"))))
        else:
            self.stdout.write(self.style.ERROR(f"❌ Failed: {result.get('reason')}"))
            if result.get("desc"):
                self.stdout.write(self.style.ERROR(f"📄 Description: {result.get('desc')}"))
