const pdf = require("pdf-creator-node");
const fs = require("fs");

const pdfBuilder = async (
  templatePath,
  fileName,
  outputFolder,
  orientation,
  data
) => {
  const date = new Date();
  const html = fs.readFileSync(templatePath, "utf8");

  const formattedDateFileName =
    date.toISOString().replace(/:/g, "-") + `-${fileName}.pdf`;
  const pdfFilePath = `./public/${outputFolder}/${formattedDateFileName}`;

  const options = {
    format: "Legal",
    orientation: orientation,
    border: "10mm",
  };

  const document = {
    html,
    data,
    path: pdfFilePath,
    type: "",
  };
  try {
    const pdfResponse = await pdf.create(document, options);
    return {
      file_path: pdfFilePath,
      file_name: formattedDateFileName,
      pdf_info: pdfResponse,
    };
  } catch (err) {
    console.error(err);
    return err;
  }
};

const pdfBuilderA5 = async (
  templatePath,
  fileName,
  outputFolder,
  orientation,
  data
) => {
  const date = new Date();
  const html = fs.readFileSync(templatePath, "utf8");

  const formattedDateFileName =
    date.toISOString().replace(/:/g, "-") + `-${fileName}.pdf`;
  const pdfFilePath = `./public/${outputFolder}/${formattedDateFileName}`;

  const options = {
    format: "Legal", // ✅ Set paper size to A5
    orientation: orientation, // "portrait" or "landscape"
    border: "5mm",
  };

  const document = {
    html,
    data,
    path: pdfFilePath,
    type: "",
  };
  try {
    const pdfResponse = await pdf.create(document, options);
    return {
      file_path: pdfFilePath,
      file_name: formattedDateFileName,
      pdf_info: pdfResponse,
    };
  } catch (err) {
    console.error(err);
    return err;
  }
};

module.exports = { pdfBuilder, pdfBuilderA5 };
