"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.razorpayWebhook = exports.requestRazorpayPayment = void 0;
const functions = require("firebase-functions");
const payment_functions_1 = require("./payment-functions");
const random = require("randomstring");
const collections_1 = require("./collections");
exports.requestRazorpayPayment = functions.https.onCall(async (request, response) => {
    try {
        //const orderId = request.orderId;
        const orderId = random.generate(12);
        await (0, payment_functions_1.createOrder)(request.timeSlotId, request.userId, orderId);
        return orderId;
    }
    catch (e) {
        throw e;
    }
});
exports.razorpayWebhook = functions.https.onRequest(async (request, response) => {
    var _a, _b, _c, _d, _e, _f;
    console.log("data : " + JSON.stringify(request.body));
    try {
        const { amount, currency, fee, method, notes } = request.body.payload.payment.entity;
        const myOrder = await collections_1.orderCol.doc(notes.order_id).get();
        if (myOrder.data() === undefined) {
            throw "order is undefined";
        }
        const timeSlot = await collections_1.timeSlotCol.doc((_a = myOrder.data()) === null || _a === void 0 ? void 0 : _a.timeSlotId).get();
        const doctor = await collections_1.doctorCol.doc((_b = timeSlot.data()) === null || _b === void 0 ? void 0 : _b.doctorId).get();
        const user = (await collections_1.usersCol.doc((_c = myOrder.data()) === null || _c === void 0 ? void 0 : _c.userId).get()).data();
        const bookByWho = {
            displayName: user === null || user === void 0 ? void 0 : user.displayName,
            photoUrl: "",
            userId: (_d = myOrder.data()) === null || _d === void 0 ? void 0 : _d.userId,
        };
        const confirmPaymentData = {
            orderId: myOrder.id,
            timeSlotId: timeSlot.id,
            paymentMethod: payment_functions_1.PaymentMethod.Paystack,
            paymentStatus: payment_functions_1.PaymentStatus.PaymentSuccess,
            amount: amount,
            currency: currency,
            fee: fee,
            paymentType: method,
            bookByWho: bookByWho,
            doctor: {
                doctorName: (_e = doctor.data()) === null || _e === void 0 ? void 0 : _e.doctorName,
                doctorPicture: (_f = doctor.data()) === null || _f === void 0 ? void 0 : _f.doctorPicture,
            },
            doctorId: doctor.id,
        };
        await (0, payment_functions_1.confirmPayment)(confirmPaymentData);
        console.log("payment success");
        response.send();
    }
    catch (err) {
        throw err;
    }
});
//# sourceMappingURL=razorpay-functions.js.map