import { isMainThread, parentPort } from "node:worker_threads";
import {
  buildFinalizeLogResult,
  type FinalizeLogJob,
  type FinalizeLogResult,
} from "./logFinalizer";

if (!isMainThread && parentPort !== null) {
  const port = parentPort;
  port.on("message", (msg: { id: string; job: FinalizeLogJob }) => {
    let result: FinalizeLogResult;
    try {
      result = buildFinalizeLogResult(msg.job);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      result = {
        log: msg.job.log,
        upstreamUrl: msg.job.upstreamUrl,
        error: message,
      };
    }
    port.postMessage({ id: msg.id, result });
  });
}
