const axios = require("axios");
const FormData = require("form-data");
const pdf = require("pdf-creator-node");
const fs = require("fs");
const emailBuilder = require("../../helpers/transporter");
const {pdfBuilder} = require("../../helpers/pdfBuilder");

const FILES_URL_CONTAINER = "https://api.buildhubware.com/public/rpaf-build-credit-application-upload/";

exports.buildcreditMailer = async (req, res, next) => {
  const {
    company_name,
    bank_branch_name,
    bank_account_name,
    bank_account_number,
    customer_name,
    file_name_signature,
    bank_email,
    agent_email,
  } = req.body;

  const date = new Date();
  const dateOptions = {
    weekday: undefined,
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    hour12: true,
  };
  const formattedDate = date.toLocaleString("en-US", dateOptions);

  try {
    const axiosResponse = await axios.get(`${FILES_URL_CONTAINER}${file_name_signature}`, {
      responseType: "arraybuffer",
    });
    const imageBase64 = Buffer.from(axiosResponse.data, "binary").toString("base64");

    const templatePath = __dirname + "/../../helpers/email-templates/buildcredit.html";
    const data = {
      date: formattedDate,
      compName: company_name,
      bankBranch: bank_branch_name,
      accName: bank_account_name,
      accNum: bank_account_number,
      signatory: customer_name,
      signature: imageBase64,
      name: customer_name,
    };
    const pdfResponse = await pdfBuilder(templatePath, "build-credit-letter", "pdf-files", "portrait", data);
    const receivers = [bank_email];
    const ccs = [agent_email];
    const attachments = [
      {
        filename: pdfResponse.file_name,
        path: pdfResponse.file_path,
        contentType: "application/pdf",
      },
    ];

    if (receivers.length > 0) {
      const emailResponse = await emailBuilder(
        receivers,
        ccs,
        "Build Credit Authorization Letter",
        false,
        "",
        attachments
      );
      res.status(200).json({ success: true, msg: "Email sent successfully." });
    } else {
      res.status(200).json({ success: false, msg: "No receivers found." });
    }
  } catch (err) {
    console.error(err);
    next(err);
  }
};
