/// <reference lib="webworker" />
import {
  WORKER_PROTOCOL_VERSION,
  workerError,
  type WorkerRequest,
  type WorkerResponse,
} from "../regex/execution/worker-protocol";
import { generateCandidateSubjects } from "../regex/generation/generate-candidates";
import type {
  GenerationWorkerOperation,
  GenerationWorkerResult,
} from "../regex/generation/generation.types";

const scope = self as DedicatedWorkerGlobalScope;

scope.onmessage = (
  event: MessageEvent<WorkerRequest<GenerationWorkerOperation>>,
) => {
  const request = event.data;
  if (request.protocolVersion !== WORKER_PROTOCOL_VERSION) return;
  let response: WorkerResponse<GenerationWorkerResult>;
  try {
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: true,
      payload: {
        kind: "generate",
        result: generateCandidateSubjects(request.payload.request),
      },
    };
  } catch (error) {
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: false,
      error: workerError(error),
    };
  }
  scope.postMessage(response);
};
