import requests
from datetime import date
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings
from shop.models import Order, PaymentLog
from django.contrib import messages  # Not used in command, but for reference

class Command(BaseCommand):
    help = 'Charge next installment for active installment orders'

    def handle(self, *args, **options):
        today = date.today()
        
        # Get orders due for payment
        orders = Order.objects.filter(
            payment_type='installment',
            status='Active',                    # or 'Partially Paid'
            next_due_date__lte=today,
            flutterwave_token__isnull=False,
            installments_paid__lt=models.F('total_installments')
        ).select_related('user')

        self.stdout.write(f"Found {orders.count()} orders due for installment charging.")

        success_count = 0
        failed_count = 0

        for order in orders:
            try:
                amount_ngn = round(order.total / order.total_installments, 2)

                payload = {
                    "token": order.flutterwave_token,
                    "amount": str(amount_ngn),
                    "currency": "NGN",
                    "email": order.user.email,
                    "tx_ref": f"bx-rec-{order.id}-{timezone.now().strftime('%Y%m%d%H%M%S')}",
                    "narration": f"Installment payment for Order #{order.id}"
                }

                headers = {
                    "Authorization": f"Bearer {settings.FLW_SECRET_KEY}",
                    "Content-Type": "application/json"
                }

                response = requests.post(
                    "https://api.flutterwave.com/v3/tokenized-charges",
                    json=payload,
                    headers=headers,
                    timeout=20
                )

                data = response.json()

                if response.status_code in (200, 201) and data.get('status') == "success":
                    # Success
                    order.installments_paid += 1
                    order.next_due_date = order.next_due_date.replace(day=order.next_due_date.day + 30)  # Next month
                    if order.installments_paid >= order.total_installments:
                        order.status = 'Paid'
                    order.save()

                    PaymentLog.objects.create(
                        order=order,
                        amount=amount_ngn,
                        status='success',
                        flutterwave_reference=data['data']['flw_ref'],  # or tx_ref
                        message=f"Installment {order.installments_paid}/{order.total_installments} charged successfully"
                    )

                    self.stdout.write(self.style.SUCCESS(f"✓ Charged Order #{order.id} - ₦{amount_ngn}"))
                    success_count += 1

                else:
                    self.stdout.write(self.style.ERROR(f"✗ Failed Order #{order.id}: {data.get('message')}"))
                    failed_count += 1

            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Error charging Order #{order.id}: {e}"))
                failed_count += 1

        self.stdout.write("\n=== Summary ===")
        self.stdout.write(self.style.SUCCESS(f"Successful charges: {success_count}"))
        self.stdout.write(self.style.ERROR(f"Failed charges: {failed_count}"))