const { sendTaskEmail } = require("../../email/sendemail");
const generateEmailTemplate = require("../../email/generateTemplate");
const { InstanceEndpoints } = require("../../utils/instanceMgr");

/**
 * @description Send notification email to the user
 * @param userEmail
 * @param jobs
 * @param partialPayments
 * @param logger
 * @param logMeta
 * @returns {Promise<void>}
 */
const sendPaymentNotificationEmail = async (userEmail, jobs, partialPayments, logger, logMeta) => {
  try {
    await sendTaskEmail({
      to: userEmail,
      subject: `New Payment(s) Received - RO ${jobs.jobs.map((j) => j.ro_number).join(", ")}`,
      type: "html",
      html: generateEmailTemplate({
        header: "New Payment(s) Received",
        subHeader: "",
        body: jobs.jobs
          .map(
            (job) =>
              `<p style="color: #0a0a0a; font-weight: normal; padding-top: 0; padding-right: 0; padding-bottom: 0; padding-left: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; margin: 0 0 0 0px; Margin: 0 0 0 0px; line-height: 1.2; margin-bottom: 0px; Margin-bottom: 0px; font-size: 90%;">Reference: <a href="${InstanceEndpoints()}/manage/jobs/${job.id}" style="color: #2199e8; text-decoration: none; font-weight: normal; padding: 0; text-align: left; font-family: 'Montserrat', 'Montserrat Alternates', sans-serif; font-size: 90%; line-height: 1.2;">${job.ro_number || "N/A"}</a> | ${job.ownr_co_nm ? job.ownr_co_nm : `${job.ownr_fn || ""} ${job.ownr_ln || ""}`.trim()} | ${`${job.v_model_yr || ""} ${job.v_make_desc || ""} ${job.v_model_desc || ""}`.trim()} | $${partialPayments.find((p) => p.jobid === job.id).amount}</p>`
          )
          .join("")
      })
    });
  } catch (error) {
    logger.log("intellipay-postback-email-error", "ERROR", "api", null, {
      message: error.message,
      jobs,
      ...logMeta
    });
  }
};

module.exports = sendPaymentNotificationEmail;
