const { generateOrderId, getReqInformation } = require("../../utils/Common");
const { createOrder, getPaymentDetailById } = require("../../utils/Razorpay");
const envCredential = require("../../config");
const { error, success } = require("../../handlers");
const {
  Transaction,
  PayOnAccess,
  FeaturedProperty,
  Property,
  Plan,
  User,
} = require("../../models");
const { PaymentTypes } = require("../../utils/Enum");
const RAZOR_PAY_KEY_ID = envCredential.RAZOR_PAY_KEY_ID;
const moment = require("moment");

const pay = async (req, res) => {
  try {
    let payload = req.body,
      orderData = {};
    let user = req?.session?.user;
    const { baseUrl } = getReqInformation(req);
    payload["transactionId"] = generateOrderId();
    payload["amount"] = payload?.amount;
    payload["userId"] = user?.id;
    orderData["currency"] = "INR";
    orderData["receipt"] = payload["transactionId"];
    orderData["payment_capture"] = 1;
    orderData["amount"] = payload?.amount * 100;
    let callbackURL = "/properties/" + payload?.propertyId;
    if (payload?.paymentType == PaymentTypes.FEATURED) {
      if (payload?.planId) {
        orderData["notes"] = {};
        orderData["notes"]["planId"] = payload?.planId;
      }
      callbackURL = "/properties/my-properties";
    } else if (payload?.paymentType == PaymentTypes.USERPLAN) {
      if (payload?.planId) {
        orderData["notes"] = {};
        orderData["notes"]["planId"] = payload?.planId;
      }
      callbackURL = "/";
    }

    let order = await createOrder(orderData);
    if (order) {
      payload["orderId"] = order?.id;
      await Transaction.create(payload);
    }
    console.log(order, "=-=-", order?.id);
    return res.render("razorpay/index.ejs", {
      orderId: order?.id,
      RAZOR_PAY_KEY_ID,
      baseUrl,
      description: payload?.description,
      user: user,
      callbackURL,
    });
  } catch (err) {
    console.log(err);
    return res.redirect("/");
  }
};

const successPayment = async (req, res) => {
  console.log(req, "=-=-=-=req-=-=-=-res=-=-=-", res);
  let paymentId = req.params?.paymentId;
  try {
    console.log(req.params, "=-=-=-=--req.query=-=", req.query);
    console.log(paymentId, "=-=-==-paymentId=-=-=-=-");
    let payment = await getPaymentDetailById(paymentId);
    console.log(payment);
    return res.render("razorpay/success.ejs", {
      payment,
      callbackURL: req?.query?.callbackURL ?? null,
    });
  } catch (err) {
    console.log(err);
    return res.redirect("/");
  }
};

const cancel = async (req, res) => {
  return res.render("razorpay/cancel.ejs", {
    callbackURL: req?.query?.callbackURL ?? null,
  });
};

const razorPayWebhook = async (req, res) => {
  try {
    let payload = req.body;
    console.log(payload, "=-=-=-payload=-=---");
    let data = payload?.payload?.payment?.entity;
    console.log(data);
    let transaction = await Transaction.findOne({
      where: {
        orderId: data?.order_id,
        status: 0,
      },
    });
    if (payload?.event == "payment.captured") {
      if (transaction) {
        if (transaction?.paymentType == PaymentTypes.PAYONACCESS) {
          await PayOnAccess.create({
            propertyId: transaction?.propertyId,
            userId: transaction?.userId,
          });
          transaction.status = 1;
          transaction.razorPayPaymentId = data?.id;
          await transaction.save();
        } else if (transaction?.paymentType == PaymentTypes.FEATURED) {
          let plan = await Plan.findOne({
            where: {
              id: data?.notes?.planId,
            },
          });
          let payloadFeatured = {
            userId: transaction?.userId,
            propertyId: transaction?.propertyId,
            planId: data?.notes?.planId,
            amount: transaction?.amount,
            expiresIn: moment().add(plan.noOfDays, "days").format("YYYY-MM-DD"),
          };
          await FeaturedProperty.create(payloadFeatured);
          await Property.update(
            { featured: 1 },
            {
              where: {
                id: transaction?.propertyId,
              },
            }
          );
          transaction.status = 1;
          transaction.razorPayPaymentId = data?.id;
          await transaction.save();
        } else if (transaction.paymentType == PaymentTypes.USERPLAN) {
          let date = moment().add(30, "days").format("YYYY-MM-DD");
          if (data?.notes?.planId) {
            let plan = await Plan.findOne({
              where: {
                id: data?.notes?.planId,
              },
            });
            if (plan) {
              date = moment().add(plan?.noOfDays, "days").format("YYYY-MM-DD");
            }
          }
          transaction.status = 1;
          transaction.razorPayPaymentId = data?.id;
          await transaction.save();
          let user = await User.findByPk(transaction.userId);
          if (user) {
            user.planActivationDate = date;
            await user.save();
          }
        }
      }
    } else if (payload?.event == "payment.failed") {
      transaction.status = 2;
      transaction.razorPayPaymentId = data?.id;
      transaction.reason = data?.error_description;
      await transaction.save();
    }
    return success(res, {
      msg: "Status updated successfully!!",
      data: [payload],
    });
  } catch (err) {
    console.log(err);
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

const createRazorPayOrder = async (req, res) => {
  try {
    let payload = req.body,
      orderData = {};
    let user = req?.user;
    payload["transactionId"] = generateOrderId();
    payload["amount"] = payload?.amount;
    payload["userId"] = user?.id;
    orderData["currency"] = "INR";
    orderData["receipt"] = payload["transactionId"];
    orderData["payment_capture"] = 1;
    orderData["amount"] = payload?.amount * 100;
    if (payload?.paymentType == PaymentTypes.FEATURED) {
      if (payload?.planId) {
        orderData["notes"] = {};
        orderData["notes"]["planId"] = payload?.planId;
      }
    } else if (payload?.paymentType == PaymentTypes.USERPLAN) {
      if (payload?.planId) {
        orderData["notes"] = {};
        orderData["notes"]["planId"] = payload?.planId;
      }
    }

    let order = await createOrder(orderData);
    if (order) {
      payload["orderId"] = order?.id;
      await Transaction.create(payload);
    }
    return success(res, {
      msg: "Order created successfully!!",
      data: [order],
    });
  } catch (err) {
    return error(res, {
      msg: "Something went wrong!!",
    });
  }
};

module.exports = {
  pay,
  successPayment,
  cancel,
  razorPayWebhook,
  createRazorPayOrder,
};
