const fs = require('fs')
const { PDFDocument } = require('pdf-lib')
const path = require('path')

async function modifyPDF(filepath) {
  // Load the existing PDF
  const existingPdfBytes = fs.readFileSync(path.join(__dirname, '/../../src/renderer/', filepath))

  // Load the PDF document
  const pdfDoc = await PDFDocument.load(existingPdfBytes)

  // Embed the font for text replacement
  const pages = pdfDoc.getPages()
  const firstPage = pages[0]

  // Replace text based on your data object
  const data = { f1: 'Nom', f2: 'Prenom', f3: 23 }

  // Example of replacing placeholders
  firstPage.drawText(data.f1, { x: 120, y: 700, size: 12 })
  firstPage.drawText(data.f2, { x: 120, y: 680, size: 12 })
  firstPage.drawText(String(data.f3), { x: 120, y: 660, size: 12 })

  // Save the modified PDF
  const pdfBytes = await pdfDoc.save()
  fs.writeFileSync('releves_modified.pdf', pdfBytes)

  console.log('PDF modified successfully!')
}

module.exports = {
  modifyPDF
}
