/// <reference lib="webworker" />
import { requireSyntaxProvider } from "../regex/syntax/provider-registry";
import {
  WORKER_PROTOCOL_VERSION,
  workerError,
  type SyntaxWorkerOperation,
  type SyntaxWorkerResult,
  type WorkerRequest,
  type WorkerResponse,
} from "../regex/execution/worker-protocol";

const scope = self as DedicatedWorkerGlobalScope;

scope.onmessage = async (
  event: MessageEvent<WorkerRequest<SyntaxWorkerOperation>>,
) => {
  const request = event.data;
  if (request.protocolVersion !== WORKER_PROTOCOL_VERSION) return;
  let response: WorkerResponse<SyntaxWorkerResult>;
  try {
    const flavour = request.payload.request.flavour;
    const provider = requireSyntaxProvider(flavour);
    const payload: SyntaxWorkerResult =
      request.payload.kind === "parse-pattern"
        ? {
            kind: "parse-pattern",
            result: await provider.parsePattern(request.payload.request),
          }
        : {
            kind: "parse-replacement",
            result: await provider.parseReplacement(request.payload.request),
          };
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: true,
      payload,
    };
  } catch (error) {
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: false,
      error: workerError(error),
    };
  }
  scope.postMessage(response);
};
