const { PDFDocument } = require("pdf-lib");

const mergePDFBuffers = async (buffers = []) => {

  const mergedPdf = await PDFDocument.create();

  for (const buffer of buffers) {

    const pdf = await PDFDocument.load(buffer);

    const copiedPages = await mergedPdf.copyPages(
      pdf,
      pdf.getPageIndices(),
    );

    copiedPages.forEach((page) => {
      mergedPdf.addPage(page);
    });
  }

  const mergedBytes = await mergedPdf.save();

  return Buffer.from(mergedBytes);
};

module.exports = mergePDFBuffers;