"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestKioskCode = exports.requestPaymentToken = exports.createOrderPaymob = exports.requestPaymobUserToken = exports.paymobPaymentSuccessHTTPMessage = exports.paymobPaymentWebhook = exports.paymobCreateOrder = void 0;
const paymob_model_1 = require("./../model/paymob-model");
const axios_1 = require("axios");
const functions = require("firebase-functions");
const payment_functions_1 = require("../payment-functions");
const random = require("randomstring");
const collections_1 = require("../collections");
const constants_1 = require("../constants");
exports.paymobCreateOrder = functions.https.onCall(async (request, response) => {
    try {
        const timeSlotId = request.timeSlotId;
        const userId = request.userId;
        const paymentType = request.paymentType;
        // console.log("payment type : " + paymentType);
        console.log("userId : " + userId);
        console.log("timeSlotId : " + timeSlotId);
        const payMobApiKey = process.env.PAYMOB_API_KEY;
        if (payMobApiKey == undefined) {
            throw "paymob api key is undefined";
        }
        const timeSlot = (await collections_1.timeSlotCol.doc(timeSlotId).get()).data();
        const user = (await collections_1.usersCol.doc(userId).get()).data();
        if (user === undefined) {
            throw "user is undefined";
        }
        if (timeSlot === undefined) {
            throw "time slot is undefined";
        }
        const orderId = random.generate(12);
        const paymobResponse = await (0, exports.requestPaymobUserToken)(payMobApiKey);
        await (0, payment_functions_1.createOrder)(request.timeSlotId, request.userId, orderId);
        const priceInCent = timeSlot.price / 10;
        if (priceInCent < 10) {
            throw "price is less than 10";
        }
        console.log("random order id : " + orderId);
        console.log("Paymob User token : " + paymobResponse.token);
        const paymobOrderData = await (0, exports.createOrderPaymob)(paymobResponse.token, priceInCent, orderId, timeSlot, timeSlotId);
        const paymobFinalToken = await (0, exports.requestPaymentToken)(paymobResponse.token, priceInCent, user, paymobOrderData.id.toString(), paymentType);
        if (paymentType == paymob_model_1.PaymobPaymentType.kiosk) {
            const kioskCode = await (0, exports.requestKioskCode)(paymobFinalToken);
            return { token: paymobFinalToken, kioskCode: kioskCode };
        }
        return { token: paymobFinalToken };
    }
    catch (error) {
        throw error;
    }
});
exports.paymobPaymentWebhook = functions.https.onRequest(async (request, response) => {
    var _a, _b, _c, _d, _e, _f;
    console.log("data : " + JSON.stringify(request.body));
    const paymobTransactionData = request.body;
    const myOrder = await collections_1.orderCol
        .doc(paymobTransactionData.obj.order.merchant_order_id)
        .get();
    response.send();
    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.PayMob,
        paymentStatus: payment_functions_1.PaymentStatus.PaymentSuccess,
        amount: paymobTransactionData.obj.order.amount_cents,
        currency: paymobTransactionData.obj.order.currency,
        fee: paymobTransactionData.obj.order.commission_fees.toString(),
        paymentType: paymobTransactionData.obj.source_data.type,
        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");
    // Send the HTML response
    response.status(200);
});
exports.paymobPaymentSuccessHTTPMessage = functions.https.onRequest((request, response) => {
    // Set the Content-Type header to indicate that the response is HTML
    response.setHeader("Content-Type", "text/html");
    // Your HTML content
    const html = `
    <html>
    <head>
      <style>
        body {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
          margin: 0;
        }
      </style>
    </head>
    <body>
      <h1>Payment Success!</h1>
    </body>
    </html>
  `;
    // Send the HTML response
    response.status(200).send(html);
});
const requestPaymobUserToken = async (paymobApiKey) => {
    try {
        const requestData = {
            api_key: paymobApiKey,
        };
        const responseAxios = await axios_1.default.post("https://accept.paymob.com/api/auth/tokens", JSON.stringify(requestData), {
            headers: {
                // Overwrite Axios's automatically set Content-Type
                "Content-Type": "application/json",
            },
        });
        console.log("Success get user token");
        const paymobResponse = responseAxios.data;
        return paymobResponse;
    }
    catch (error) {
        console.log(error);
        throw error;
    }
};
exports.requestPaymobUserToken = requestPaymobUserToken;
const createOrderPaymob = async (token, price, orderId, timeSlot, timeSlotId) => {
    try {
        console.log("Initiate Create Order");
        const orderReqData = {
            auth_token: token,
            delivery_needed: "false",
            amount_cents: price,
            currency: "EGP",
            merchant_order_id: orderId,
            items: [
                {
                    name: "TimeSlot book " + timeSlotId,
                    amount_cents: price,
                    description: "Timeslot Booking at " + timeSlot.timeSlot.toDate().toDateString(),
                    quantity: "1",
                },
            ],
        };
        console.log("orderReqData : " + JSON.stringify(orderReqData));
        const responseAxiosOrder = await axios_1.default.post("https://accept.paymob.com/api/ecommerce/orders", JSON.stringify(orderReqData), {
            headers: {
                "Content-Type": "application/json",
            },
        });
        console.log("Success crete order paymob");
        const paymobOrderData = responseAxiosOrder.data;
        return paymobOrderData;
    }
    catch (error) {
        throw error;
    }
};
exports.createOrderPaymob = createOrderPaymob;
const requestPaymentToken = async (paymobReqToken, price, user, paymobOrderDataId, paymentType) => {
    try {
        const orderReqDataFinal = {
            auth_token: paymobReqToken,
            amount_cents: price,
            expiration: 3600,
            order_id: paymobOrderDataId,
            billing_data: {
                apartment: "NA",
                email: user.email,
                floor: "NA",
                first_name: user.displayName,
                street: "NA",
                building: "NA",
                phone_number: "NA",
                shipping_method: "NA",
                postal_code: "NA",
                city: "NA",
                country: "NA",
                last_name: "NA",
                state: "NA",
            },
            currency: "EGP",
            integration_id: paymentType == paymob_model_1.PaymobPaymentType.card
                ? constants_1.integrationIdCard
                : constants_1.integrationIdKiosk,
            lock_order_when_paid: "false",
        };
        const paymobFinalCall = await axios_1.default.post("https://accept.paymob.com/api/acceptance/payment_keys", JSON.stringify(orderReqDataFinal), {
            headers: {
                "Content-Type": "application/json",
            },
        });
        const finalResponse = paymobFinalCall.data;
        console.log("final call : " + JSON.stringify(paymobFinalCall.data));
        console.log("Success get payment token : " + finalResponse.token);
        return finalResponse.token;
    }
    catch (error) {
        throw error;
    }
};
exports.requestPaymentToken = requestPaymentToken;
const requestKioskCode = async (finalToken) => {
    try {
        const kioskData = {
            source: {
                identifier: "AGGREGATOR",
                subtype: "AGGREGATOR",
            },
            payment_token: finalToken,
        };
        const responseAxiosKiosk = await axios_1.default.post("https://accept.paymob.com/api/acceptance/payments/pay", JSON.stringify(kioskData), {
            headers: {
                "Content-Type": "application/json",
            },
        });
        const kioskCodeResponse = responseAxiosKiosk.data;
        console.log("kiosk data : " + JSON.stringify(kioskCodeResponse));
        return kioskCodeResponse["id"].toString();
    }
    catch (e) {
        console.log(e);
        throw e;
    }
};
exports.requestKioskCode = requestKioskCode;
//# sourceMappingURL=paymob-functions.js.map