"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withdrawRequest = void 0;
const functions = require("firebase-functions");
const collections_1 = require("./collections");
const user_wallet_functions_1 = require("./user-wallet-functions");
const admin = require("firebase-admin");
const db = admin.firestore();
const { firestore } = require("firebase-admin");
/**
 * Doctor withdrawal request, this function will get called by @DoctorApp
 * doctor balance will be set to 0 and their request will be put to "WithdrawRequest" collection in firebase,
 * but the status will be pending, admin should send the real balance to the doctor account, and set the withdrawal status to succeed
 */
exports.withdrawRequest = functions.firestore
    .document("/WithdrawRequest/{withdrawRequestId}")
    .onCreate(async (snapshot, context) => {
    var _a;
    let userId = snapshot.data().userId;
    console.log("user Id : " + userId);
    console.log("snapshot data : " + JSON.stringify(snapshot.data()));
    let withdrawSettings = await db
        .collection("Settings")
        .doc("withdrawSetting")
        .get();
    const doctorId = (_a = (await collections_1.usersCol.doc(userId).get()).data()) === null || _a === void 0 ? void 0 : _a.doctorId;
    console.log("doctor id : " + doctorId);
    //decrease doctor balance amount
    // let doctor = await db.collection("Doctors").doc(doctorId).get();
    let useWallet = await (0, user_wallet_functions_1.getUserWallet)(userId);
    let doctorBalance = useWallet.balance;
    console.log("balance : " + doctorBalance);
    if (doctorBalance <= 0) {
        snapshot.ref.delete();
        return Promise.reject();
    }
    let adminFee = (doctorBalance / 100) * withdrawSettings.data().percentage;
    let taxCut = (doctorBalance / 100) * withdrawSettings.data().tax;
    let totalAmount = doctorBalance - (adminFee + taxCut);
    await snapshot.ref.update({
        amount: doctorBalance,
        adminFee: adminFee.toFixed(2),
        tax: taxCut.toFixed(2),
        totalWithdraw: totalAmount.toFixed(2),
        status: "pending",
        createdAt: firestore.Timestamp.fromDate(new Date()),
    });
    //let balanceNow = (doctorBalance -= snapshot.data().amount);
    await (0, user_wallet_functions_1.resetWalletBalance)(userId);
    // await doctor.ref.update({ balance: 0 });
    //add transaction
    await db.collection("Transaction").add({
        userId: userId,
        withdrawMethod: snapshot.data().withdrawMethod,
        amount: doctorBalance,
        status: "pending",
        type: "withdraw",
        createdAt: firestore.Timestamp.fromDate(new Date()),
        withdrawRequestId: snapshot.id,
    });
    return Promise.resolve();
});
//# sourceMappingURL=withdraw-functions.js.map