/// <reference lib="webworker" />
import {
  benchmarkEcmaScriptSample,
  ecmaScriptAnalysisIdentity,
  probeEcmaScriptGrowth,
} from "../regex/analysis/ecmascript-analysis";
import type {
  AnalysisWorkerOperation,
  AnalysisWorkerResult,
} from "../regex/analysis/analysis.types";
import {
  WORKER_PROTOCOL_VERSION,
  workerError,
  type WorkerRequest,
  type WorkerResponse,
} from "../regex/execution/worker-protocol";

const scope = self as DedicatedWorkerGlobalScope;

scope.onmessage = (
  event: MessageEvent<WorkerRequest<AnalysisWorkerOperation>>,
) => {
  const request = event.data;
  if (request.protocolVersion !== WORKER_PROTOCOL_VERSION) return;
  let response: WorkerResponse<AnalysisWorkerResult>;
  try {
    let payload: AnalysisWorkerResult;
    if (request.payload.kind === "identity") {
      payload = { kind: "identity", result: ecmaScriptAnalysisIdentity() };
    } else if (request.payload.kind === "benchmark-sample") {
      payload = {
        kind: "benchmark-sample",
        result: benchmarkEcmaScriptSample(request.payload.request),
      };
    } else {
      payload = {
        kind: "growth-probe",
        result: probeEcmaScriptGrowth(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);
};
