from subscription.models import Subscription
from django.core.management import BaseCommand
from apps.order.models import Order
from django.conf import settings
from django.db import transaction
import crayons


class Command(BaseCommand):
    help = 'Delete all the orders created by the faulty billing'

    def handle(self, *args, **options):
        with transaction.atomic():
            problems_subs = []
            for sub in Subscription.objects.all():
                orders = Order.objects.filter(
                    status=settings.ORDER_STATUS_PENDING,
                    subscription=sub
                ).distinct()
                if orders.count() > 1:
                    problems_subs.append(sub)

            for sub in problems_subs:
                orders = list(Order.objects.filter(
                    subscription=sub,
                    status=settings.ORDER_STATUS_PENDING).order_by('-lines__est_dispatch_date').all())
                last_order = orders.pop()
                for order in orders:
                    order.delete()
                sub.next_order = last_order.lines.first().est_dispatch_date
                sub.save()
        print('Done')
