import stripe

from configs.firebase import SANDBOX, SERVER_TIMESTAMP, db
from functions.Invoices import createCustomer, getCustomer, getStripeCreds
from functions.Response import API_Error
from functions.Users import getEnterpriseAdmin, getUser


def orderCharge(params:dict):
    id = params.get('id')
    currentUser = params.get('currentUser')
    enterpriseId, isProUser, isEnterpriseAdmin = currentUser.get('enterpriseId'), currentUser.get('isProUser'), currentUser.get('isEnterpriseAdmin')
    orderRef = db.collection("orders").document(id)
    if isProUser: enterpriseId = "BSSLIiNy1oIgVazwv0iO" if SANDBOX else "cfbZh6XFBG3usCcUwpRE"
    stripeCreds = getStripeCreds(enterpriseId)
    adminUid = getEnterpriseAdmin(enterpriseId) if not isProUser else currentUser.get("uid")
    if stripeCreds:
        stripe.api_key = stripeCreds.get('apiSecret')
        customer = getCustomer(adminUid, enterpriseId)
        if not customer:
            customer = createCustomer(getUser(adminUid), stripeCreds)
        if customer:
            customerId = customer.get('customerId')
            description = ""
            metadata = dict(uid=adminUid, invoiceId=id, enterpriseId=enterpriseId, displayName=currentUser.get("displayName"))
            try:
                invoiceItem = stripe.InvoiceItem.create(customer =customerId, amount = 3, currency="USD", description=description, metadata = metadata)
                orderRef.update({"charged": True, "chargedAt": SERVER_TIMESTAMP, "invoiceItemId": invoiceItem.id if invoiceItem else None})
                return dict(invoiceItem)
            except Exception as e:
                print(e)
                raise API_Error(str(e), 400)
        else:raise API_Error("Customer not found.", 404)
    else:raise API_Error("Stripe API Keys not saved.", 404)

def orderChargeInvoices(params):
    users = db.collection("users").where("isEnterpriseAdmin", "==", True).get()
    for user in users:
        if enterpriseId == "cfbZh6XFBG3usCcUwpRE" : continue
        enterpriseId = "cfbZh6XFBG3usCcUwpRE" if not SANDBOX else "BSSLIiNy1oIgVazwv0iO"
        uid = user.get('uid')
        customer = getCustomer(uid, enterpriseId)
        stripeCreds =  getStripeCreds(enterpriseId)
        if not stripeCreds: continue
        if not customer:
            customer = createCustomer(user,stripeCreds)
        if customer:
            customerId = customer.get('customerId')
            stripe.api_key = stripeCreds.get('apiSecret')
            stripeInvoice = stripe.Invoice.create(customer = customerId, collection_method='charge_automatically', description="Order Charges 3cents/order")
            stripeInvoice = dict(stripe.Invoice.finalize_invoice(stripeInvoice.get('id')))
            if stripeInvoice.get('amount_due',0) > 0:db.collection("weeklyInvoices").document(stripeInvoice.get('id')).set(dict(stripeInvoice))