import ELK from "elkjs/lib/elk.bundled.js";

import type { ElkNode } from "elkjs";

const elk = new ELK();

export interface ElkWorkerRequest {
  type: "layout";
  graph: ElkNode;
}

export interface ElkWorkerResponse {
  type: "result" | "error";
  graph?: ElkNode;
  message?: string;
}

self.onmessage = async (event: MessageEvent<ElkWorkerRequest>) => {
  if (event.data.type !== "layout") return;

  try {
    const result = await elk.layout(event.data.graph);
    (self as unknown as Worker).postMessage({
      type: "result",
      graph: result,
    } satisfies ElkWorkerResponse);
  } catch (error) {
    (self as unknown as Worker).postMessage({
      type: "error",
      message: error instanceof Error ? error.message : String(error),
    } satisfies ElkWorkerResponse);
  }
};
