import * as functions from "firebase-functions";
import { usersCol } from "./collections";
import { getUserWallet, resetWalletBalance } from "./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
 */
export const withdrawRequest = functions.firestore
  .document("/WithdrawRequest/{withdrawRequestId}")
  .onCreate(async (snapshot, context) => {
    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 = (await usersCol.doc(userId).get()).data()?.doctorId;

    console.log("doctor id : " + doctorId);
    //decrease doctor balance amount
    // let doctor = await db.collection("Doctors").doc(doctorId).get();
    let useWallet = await 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 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();
  });
