import json

import stripe
from flask.wrappers import Request

from configs.firebase import SERVER_TIMESTAMP, db
from functions.Response import API_Error


def getWebhookSecret(enterpriseId):
    ref = db.collection('paymentPlatformsCredentials').document("STRIPE"+enterpriseId).get()
    if ref.exists:
        return ref.to_dict()
    return {}

def createInvoiceWebhook(params:dict):
    user = params.get('currentUser')
    uid, email, name, enterpriseId = user.get('uid'),  user.get('email'),  user.get('displayName'), user.get('enterpriseId')
    endpoint = "https://enterpriseapi1.riverr.app/webhooks/invoices"
    stripeCreds = db.collection('paymentPlatformsCredentials').document('STRIPE'+enterpriseId).get()
    if stripeCreds.exists:
        webhookRef = stripeCreds.reference.collection('webhooks').document('invoice')
        stripeCreds = stripeCreds.to_dict()
        apiKey = stripeCreds.get('apiKey')
        stripe.api_key = apiKey
        webhook = dict(stripe.WebhookEndpoint.create(
            url = endpoint,
            enabled_events = ["invoice.paid", "invoice.payment_succeeded", "invoice.updated"],
            description = "",
            metadata = dict(
                uid=uid,
                email=email,
                name=name,
                enterpriseId=enterpriseId
            )
        ))
        webhook = dict(
            id ="invoice",
            webhookId = webhook.get('id'),
            description = webhook.get('description'),
            events = webhook.get('enabled_events'),
            url = webhook.get('url'),
            secret = webhook.get('secret'),
            metadata = webhook.get('metadata'),
            createdAt=SERVER_TIMESTAMP,
            updatedAt = SERVER_TIMESTAMP,
            uid=uid,
            enterpriseId=enterpriseId
        )
        webhookRef.set(webhook, merge=True)
        return webhook
    raise API_Error("Stripe API Keys not saved.", 404)


def stripeInvoiceWebhook(request: Request):
    body = dict(json.loads(request.data))
    invoice = body.get('data', {}).get('object', {})
    metadata = object.get('metadata')
    if metadata:
        enterpriseId = metadata.get('enterpriseId')
        webhookCreds = getWebhookSecret(enterpriseId)

        payload = request.data.decode("utf-8")
        received_sig = request.headers.get("Stripe-Signature", None)
        event = None
        invoice= None
        try:
            event = stripe.Webhook.construct_event(
                payload, received_sig, webhookCreds.get('secret')
            )
        except ValueError as e:
            print(e)
            raise API_Error("Error while decoding event!", 400)
        except stripe.error.SignatureVerificationError:
            print("Invalid signature!")
            raise API_Error("Bad_signature", 400)
        print(
            "Received event: id={id}, type={type}".format(
                id=event.id, type=event.type
            )
        )
        if event.type == "invoice.paid" or event.type == "invoice.payment_succeeded" or event.type =="invoice.updated":
            invoice = event.data.object
            metadata = invoice.get("metadata")
            if metadata:
                invoiceId = metadata.get("invoiceId")
                if invoiceId:
                    paid = invoice.get("status") == 'paid' 
                    paidAt = SERVER_TIMESTAMP
                    ref = db.collection("invoices").document(invoiceId)
                    ref.update(dict(paid = paid, paidAt=paidAt if paid else None, updatedAt=paidAt))
                    print("INVOICE UPDATED :" , invoiceId)
                else:
                    print("NO INVOICE ID", event.id)
            else:
                print("NO METADATA", event.id)
        else:print("UNHANDLED EVENT", event.id)
    return dict(success = True, status = 200)