import type {
  ToolWorkerRequest,
  ToolWorkerResponse,
} from "../../core/plugins/worker-protocol";
import type { PdfWatermarkOptions } from "./index";
import { applyWatermark } from "./watermark";

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

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

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

    try {
      const file = files[0];
      const buffer = await file.arrayBuffer();

      const result = await applyWatermark(file.name, buffer, options, (progress) =>
        post({ type: "progress", id, progress })
      );

      post({ type: "success", id, result });
    } catch (error) {
      post({
        type: "error",
        id,
        error:
          error instanceof Error
            ? error.message
            : "Unknown error occurred while watermarking the PDF.",
      });
    }
  }
);
