"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.midtransWebhook = exports.requestMidtransPayment = void 0;
const functions = require("firebase-functions");
const collections_1 = require("../collections");
const random = require("randomstring");
const payment_functions_1 = require("../payment-functions");
const firebase_admin_1 = require("firebase-admin");
const notification_function_1 = require("../notification-function");
const midtransClient = require("midtrans-client");
exports.requestMidtransPayment = functions.https.onCall(async (request, response) => {
    try {
        // let userId = request.userId;
        let timeSlotId = request.timeSlotId;
        const choosedTimeSlot = (await collections_1.timeSlotCol.doc(timeSlotId).get()).data();
        if (!choosedTimeSlot) {
            throw new functions.https.HttpsError("not-found", "Selected Time slot not found");
        }
        /// Generate order id
        const orderId = random.generate(12);
        let snap = new midtransClient.Snap({
            isProduction: false,
            serverKey: process.env.MIDTRANS_SERVER_KEY,
            clientKey: process.env.MIDTRANS_CLIENT_KEY,
        });
        const paymentAmount = choosedTimeSlot.price * 16000; // Convert to IDR because default currency price is in USD
        let parameter = {
            transaction_details: {
                order_id: orderId,
                gross_amount: paymentAmount,
            },
            credit_card: {
                secure: true,
            },
        };
        let token = await snap
            .createTransaction(parameter)
            .then((transaction) => {
            // transaction token
            let transactionToken = transaction.token;
            console.log("transactionToken:", transactionToken);
            return transactionToken;
        });
        /// Create order in firestore database
        await collections_1.orderCol.doc(orderId).set({
            createdAt: firebase_admin_1.firestore.Timestamp.fromDate(new Date()),
            timeSlotId: request.timeSlotId,
            userId: request.userId,
            charged: false,
            status: collections_1.OrderStatus.notPay,
            paymentMethod: payment_functions_1.PaymentMethod.Midtrans,
        });
        return token;
    }
    catch (error) {
        console.log(error);
        throw error;
    }
});
exports.midtransWebhook = functions.https.onRequest(async (request, response) => {
    var _a, _b, _c, _d, _e, _f, _g;
    try {
        console.log(JSON.stringify(request.body));
        const { gross_amount, order_id, currency } = request.body;
        let order = await collections_1.orderCol.doc(order_id).get();
        if (!order.exists) {
            response.status(404).send("Order not found, with id: " + order_id);
            return;
        }
        order.ref.update({
            charged: true,
            amount: gross_amount,
            status: payment_functions_1.PaymentStatus.PaymentSuccess,
            currency: currency,
        });
        //Get user info who book this timeslot
        let bookByWho = (await collections_1.usersCol.doc((_a = order.data()) === null || _a === void 0 ? void 0 : _a.userId).get()).data();
        const timeSlot = await collections_1.timeSlotCol.doc((_b = order.data()) === null || _b === void 0 ? void 0 : _b.timeSlotId).get();
        const doctor = await collections_1.doctorCol.doc((_c = timeSlot.data()) === null || _c === void 0 ? void 0 : _c.doctorId).get();
        timeSlot.ref.update({
            charged: true,
            available: false,
            bookByWho: {
                userId: (_d = order.data()) === null || _d === void 0 ? void 0 : _d.userId,
                displayName: bookByWho === null || bookByWho === void 0 ? void 0 : bookByWho.displayName,
                photoUrl: (bookByWho === null || bookByWho === void 0 ? void 0 : bookByWho.photoUrl) ? bookByWho === null || bookByWho === void 0 ? void 0 : bookByWho.photoUrl : "",
            },
            status: "booked",
            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,
            },
            purchaseTime: firebase_admin_1.firestore.Timestamp.fromDate(new Date()),
        });
        await (0, notification_function_1.orderedTimeslotNotification)(doctor.id);
        await (0, notification_function_1.paymentSuccessNotification)((_g = order.data()) === null || _g === void 0 ? void 0 : _g.userId, order.id);
        response.status(200).send("OK");
    }
    catch (error) {
        throw error;
    }
});
//# sourceMappingURL=midtrans-functions.js.map