import * as functions from "firebase-functions";
import {
  confirmPayment,
  createOrder,
  ConfirmPayment,
  PaymentMethod,
  PaymentStatus,
} from "../payment-functions";
import * as random from "randomstring";
import {
  orderCol,
  BookByWho,
  doctorCol,
  usersCol,
  timeSlotCol,
} from "../collections";
export const requestRazorpayPayment = functions.https.onCall(
  async (request, response) => {
    try {
      //const orderId = request.orderId;
      const orderId = random.generate(12);
      await createOrder(request.timeSlotId, request.userId, orderId);
      return orderId;
    } catch (e) {
      throw e;
    }
  }
);

export const razorpayWebhook = functions.https.onRequest(
  async (request, response) => {
    console.log("data : " + JSON.stringify(request.body));
    try {
      const { amount, currency, fee, method, notes } =
        request.body.payload.payment.entity;

      const myOrder = await orderCol.doc(notes.order_id).get();
      if (myOrder.data() === undefined) {
        throw "order is undefined";
      }
      const timeSlot = await timeSlotCol.doc(myOrder.data()?.timeSlotId!).get();
      const doctor = await doctorCol.doc(timeSlot.data()?.doctorId!).get();
      const user = (await usersCol.doc(myOrder.data()?.userId!).get()).data();

      const bookByWho: BookByWho = {
        displayName: user?.displayName!,
        photoUrl: "",
        userId: myOrder.data()?.userId!,
      };
      const confirmPaymentData: ConfirmPayment = {
        orderId: myOrder.id,
        timeSlotId: timeSlot.id!,
        paymentMethod: PaymentMethod.Paystack,
        paymentStatus: PaymentStatus.PaymentSuccess,
        amount: amount,
        currency: currency,
        fee: fee,
        paymentType: method,
        bookByWho: bookByWho,
        doctor: {
          doctorName: doctor.data()?.doctorName!,
          doctorPicture: doctor.data()?.doctorPicture!,
        },
        doctorId: doctor.id,
      };

      await confirmPayment(confirmPaymentData);

      console.log("payment success");
      response.send();
    } catch (err) {
      throw err;
    }
  }
);
