import { PDFDocument } from "pdf-lib";
import type {
  ToolWorkerRequest,
  ToolWorkerResponse,
} from "../../core/plugins/worker-protocol";

function post(response: ToolWorkerResponse) {
  self.postMessage(response);
}

self.addEventListener("message", async (e: MessageEvent<ToolWorkerRequest>) => {
  const { id, input } = e.data;
  const files = input.files;

  if (!files || !Array.isArray(files) || files.length === 0) {
    post({
      type: "error",
      id,
      error: "No files provided for merging.",
    });
    return;
  }

  try {
    const mergedPdf = await PDFDocument.create();

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      post({
        type: "progress",
        id,
        progress: {
          percentage: (i / files.length) * 100,
          message: `Merging ${file.name} (${i + 1}/${files.length})...`,
        },
      });

      const fileBuffer = await file.arrayBuffer();
      const pdfDoc = await PDFDocument.load(new Uint8Array(fileBuffer));
      const copiedPages = await mergedPdf.copyPages(
        pdfDoc,
        pdfDoc.getPageIndices()
      );
      copiedPages.forEach((page) => mergedPdf.addPage(page));
    }

    post({
      type: "progress",
      id,
      progress: {
        percentage: 100,
        message: "Finalizing PDF...",
      },
    });

    const mergedPdfBytes = await mergedPdf.save();
    const blob = new Blob([mergedPdfBytes as unknown as BlobPart], {
      type: "application/pdf",
    });

    post({
      type: "success",
      id,
      result: {
        type: "files",
        files: [
          {
            name: "merged_document.pdf",
            mimeType: "application/pdf",
            blob,
            sizeAfter: blob.size,
          },
        ],
      },
    });
  } catch (error) {
    post({
      type: "error",
      id,
      error:
        error instanceof Error
          ? error.message
          : "Unknown error occurred during PDF merging",
    });
  }
});
