import json
from uncloud_pay.models import Product, Order, ProductToRecurringPeriod, Bill, Payment
from .models import VMInstance


def finalize_order(request, customer, billing_address,
                    one_time_price, pricing_plan,
                    specs):
    product = Product.objects.first()
    recurring_period_product = ProductToRecurringPeriod.objects.filter(product=product, is_default=True).first()
    order = Order.objects.create(
            owner=request.user,
            customer=customer,
            billing_address=billing_address,
            one_time_price=one_time_price,
            pricing_plan=pricing_plan,
            recurring_period= recurring_period_product.recurring_period,
            product = product,
            config=json.dumps(specs)
        )
    if order:
        bill = Bill.create_next_bill_for_order(order, ending_date=order.next_cancel_or_downgrade_date(order.starting_date))
        payment= Payment.withdraw(owner=request.user, amount=one_time_price, notes=f"BILL #{bill.id}")
        if payment:
            #Close the bill as the payment has been added
            VMInstance.create_instance(order)
            bill.close()
    
    return order, bill