import type {
  ToolWorkerRequest,
  ToolWorkerResponse,
} from "../../core/plugins/worker-protocol";
import { removeImageBackground, type BackgroundRemoverOptions } from "./remove";

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

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

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

    try {
      const file = files[0];
      const result = await removeImageBackground(
        file.name,
        file,
        options,
        self.location.origin,
        (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 removing the background.",
      });
    }
  }
);
