const fs = require("fs");
const path = require("path");
const { PDFDocument, StandardFonts, rgb } = require("pdf-lib");

exports.createCreditPdf = async ({
  creditId,
  originalInvoice,
  creditAmount,
  patient,
}) => {
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage([595, 842]); // A4

  const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
  const bold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);

  let y = 800;

  const draw = (text, size = 12, boldFont = false) => {
    page.drawText(text, {
      x: 50,
      y,
      size,
      font: boldFont ? bold : font,
      color: rgb(0, 0, 0),
    });
    y -= size + 6;
  };

  draw("GUTSCHRIFT", 20, true);
  y -= 20;

  draw(`Gutschrift-Nr.: ${creditId}`, 12, true);
  draw(`Bezieht sich auf Rechnung Nr.: ${originalInvoice.id}`);
  y -= 10;

  draw(`Patient: ${patient.firstname} ${patient.lastname}`);
  draw(`Rechnungsdatum: ${originalInvoice.invoice_date_formatted}`);
  y -= 20;

  draw("Gutschriftbetrag:", 12, true);
  draw(`${creditAmount.toFixed(2)} €`, 14, true);

  // Wasserzeichen
  page.drawText("GUTSCHRIFT", {
    x: 150,
    y: 400,
    size: 80,
    rotate: { type: "degrees", angle: -30 },
    color: rgb(0.8, 0, 0),
    opacity: 0.2,
  });

  const pdfBytes = await pdfDoc.save();

  const dir = path.join(
    __dirname,
    "..",
    "public",
    "invoices",
    new Date().getFullYear().toString(),
  );

  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

  const filePath = `/invoices/${new Date().getFullYear()}/credit-${creditId}.pdf`;
  fs.writeFileSync(path.join(__dirname, "..", "public", filePath), pdfBytes);

  return filePath;
};
