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

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["order_currency"] = "INR";
    orderData["order_id"] = payload["transactionId"];
    orderData["order_amount"] = payload?.amount;
    orderData["order_note"] = payload?.description;
    orderData["customer_details"] = {
      customer_id: `${payload.userId}`,
      customer_phone: user?.mobileNo ? `${user?.mobileNo}` : "9087654321",
    };

    let callbackURL = "/properties/" + payload?.propertyId;
    if (payload?.paymentType == PaymentTypes.FEATURED) {
      if (payload?.planId) {
        orderData["order_tags"] = {};
        orderData["order_tags"]["planId"] = `${payload?.planId}`;
      }
      callbackURL = "/properties/my-properties";
    } else if (payload?.paymentType == PaymentTypes.USERPLAN) {
      if (payload?.planId) {
        orderData["order_tags"] = {};
        orderData["order_tags"]["planId"] = `${payload?.planId}`;
      }
      callbackURL = "/";
    }

    orderData["order_meta"] = {
      return_url:
        baseUrl +
        "/cashfree/success?order_id=" +
        payload["transactionId"] +
        "&paymentType=" +
        payload?.paymentType +
        "&callbackURL=" +
        callbackURL,
    };

    let order = await createOrder(orderData);
    console.log("=-=-=order-=-=-", order);
    if (order) {
      payload["orderId"] = order?.cf_order_id;
      await Transaction.create(payload);
    }
    console.log(order, "=-=-", order?.id);
    return res.render("cashfree/index.ejs", {
      orderId: order?.id,
      paymentSessionId: order?.payment_session_id,
      CASHFREE_KEY_ID,
      CASHFREE_ENV,
      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.query?.order_id;
  let callbackURL = req.query?.callbackURL;
  try {
    console.log(req.params, "=-=-=-=--req.query=-=", req.query);
    console.log(paymentId, "=-=-==-paymentId=-=-=-=-");
    let payment = await getPaymentDetailById(paymentId);
    console.log(payment);
    if (payment && payment?.order_status != "PAID") {
      return res.redirect("/cashfree/cancel?callbackURL=" + callbackURL);
    }
    return res.render("razorpay/success.ejs", {
      payment,
      callbackURL: 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 cashFreeWebhook = async (req, res) => {
  try {
    let payload = req.body;
    console.log(payload, "=-=-=-payload=-=---");
    const order = payload?.data?.order;
    let data = payload?.data?.payment;
    console.log(data);
    let transaction = await Transaction.findOne({
      where: {
        transactionId: order?.order_id,
        status: 0,
      },
    });
    if (data.payment_status == "SUCCESS") {
      if (transaction) {
        if (transaction?.paymentType == PaymentTypes.PAYONACCESS) {
          await PayOnAccess.create({
            propertyId: transaction?.propertyId,
            userId: transaction?.userId,
          });
          transaction.status = 1;
          transaction.razorPayPaymentId = data?.cf_payment_id;
          await transaction.save();
        } else if (transaction?.paymentType == PaymentTypes.FEATURED) {
          let plan = await Plan.findOne({
            where: {
              id: order?.order_tags?.planId,
            },
          });
          let payloadFeatured = {
            userId: transaction?.userId,
            propertyId: transaction?.propertyId,
            planId: order?.order_tags?.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?.cf_payment_id;
          await transaction.save();
        } else if (transaction.paymentType == PaymentTypes.USERPLAN) {
          let date = moment().add(30, "days").format("YYYY-MM-DD");
          if (order?.order_tags?.planId) {
            let plan = await Plan.findOne({
              where: {
                id: order?.order_tags?.planId,
              },
            });
            if (plan) {
              date = moment().add(plan?.noOfDays, "days").format("YYYY-MM-DD");
            }
          }
          transaction.status = 1;
          transaction.razorPayPaymentId = data?.cf_payment_id;
          await transaction.save();
          let user = await User.findByPk(transaction.userId);
          if (user) {
            user.planActivationDate = date;
            await user.save();
          }
        }
      }
    } else if (data.payment_status == "FAILED") {
      transaction.status = 2;
      transaction.razorPayPaymentId = data?.cf_payment_id;
      transaction.reason = data?.payment_message;
      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 createCashFreeOrder = async (req, res) => {
  try {
    let payload = req.body,
      orderData = {};
    let user = req?.user;
    console.log(user, "=-=-=-=user-=-=-=");
    payload["transactionId"] = generateOrderId();
    payload["amount"] = payload?.amount;
    payload["userId"] = user?.id;
    orderData["order_currency"] = "INR";
    orderData["order_id"] = payload["transactionId"];
    orderData["order_amount"] = payload?.amount;
    orderData["order_note"] = payload?.description;
    orderData["customer_details"] = {
      customer_id: `${payload.userId}`,
      customer_phone: user?.mobileNo ? `${user?.mobileNo}` : "9087654321",
    };
    if (payload?.paymentType == PaymentTypes.FEATURED) {
      if (payload?.planId) {
        orderData["order_tags"] = {};
        orderData["order_tags"]["planId"] = `${payload?.planId}`;
      }
    } else if (payload?.paymentType == PaymentTypes.USERPLAN) {
      if (payload?.planId) {
        orderData["order_tags"] = {};
        orderData["order_tags"]["planId"] = `${payload?.planId}`;
      }
    }

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

module.exports = {
  pay,
  successPayment,
  cancel,
  cashFreeWebhook,
  createCashFreeOrder,
};
