const sendPaymentNotificationEmail = require("./sendPaymentNotificationEmail");
const { INSERT_NEW_PAYMENT, GET_BODYSHOP_BY_ID, GET_JOBS_BY_PKS } = require("../../graphql-client/queries");
const getPaymentType = require("./getPaymentType");
const moment = require("moment-timezone");

const gqlClient = require("../../graphql-client/graphql-client").client;

/**
 * @description Handle comment-based payment processing
 * @param values
 * @param decodedComment
 * @param logger
 * @param logMeta
 * @param res
 * @returns {Promise<*>}
 */
const handleCommentBasedPayment = async (values, decodedComment, logger, logMeta, res) => {
  logger.log("intellipay-postback-parsed-comment", "DEBUG", "api", null, {
    parsedComment: decodedComment,
    ...logMeta
  });

  const partialPayments = Array.isArray(decodedComment) ? decodedComment : decodedComment.payments;

  // Fetch job data
  const jobs = await gqlClient.request(GET_JOBS_BY_PKS, {
    ids: partialPayments.map((p) => p.jobid)
  });

  // Fetch bodyshop data
  const bodyshop = await gqlClient.request(GET_BODYSHOP_BY_ID, {
    id: jobs.jobs[0].shopid
  });

  const ipMapping = bodyshop.bodyshops_by_pk.intellipay_config?.payment_map;

  logger.log("intellipay-postback-jobs-fetched", "DEBUG", "api", null, {
    jobs,
    parsedComment: decodedComment,
    ...logMeta
  });

  // Create payment records
  const paymentResult = await gqlClient.request(INSERT_NEW_PAYMENT, {
    paymentInput: partialPayments.map((p) => ({
      amount: p.amount,
      transactionid: values.authcode,
      payer: "Customer",
      type: getPaymentType(ipMapping, values.cardtype),
      jobid: p.jobid,
      date: moment()
        .tz(bodyshop?.bodyshops_by_pk?.timezone ?? "UTC")
        .format("YYYY-MM-DD"),
      payment_responses: {
        data: {
          amount: values.total,
          bodyshopid: bodyshop.bodyshops_by_pk.id,
          jobid: p.jobid,
          declinereason: "Approved",
          ext_paymentid: values.paymentid,
          successful: true,
          response: values
        }
      }
    }))
  });

  logger.log("intellipay-postback-payment-success", "DEBUG", "api", null, {
    paymentResult,
    jobs,
    parsedComment: decodedComment,
    ...logMeta
  });

  // Send notification email if needed
  if (values?.origin === "OneLink" && decodedComment?.userEmail) {
    await sendPaymentNotificationEmail(decodedComment.userEmail, jobs, partialPayments, logger, logMeta);
  }

  return res.sendStatus(200);
};

module.exports = handleCommentBasedPayment;
