import { must } from "../../../../shared/src/must.js";
import { Database } from "../../../../zqlite/src/db.js";
import { createLogContext } from "../../server/logging.js";
import { StatementRunner } from "../../db/statements.js";
import { getSubscriptionState } from "./schema/replication-state.js";
import { ChangeProcessor } from "./change-processor.js";
import { applyPragmas } from "./write-worker-client.js";
import { parentPort } from "node:worker_threads";
//#region ../zero-cache/src/services/replicator/write-worker.ts
if (!parentPort) throw new Error("write-worker must be run as a worker thread");
var port = parentPort;
function createAPI() {
	let db;
	let runner;
	let processor;
	let mode;
	let lc;
	function createProcessor() {
		processor = new ChangeProcessor(must(runner), must(mode), (_lc, err) => {
			port.postMessage({ writeError: err instanceof Error ? err : new Error(String(err)) });
		});
	}
	return {
		init(dbPath, cpMode, pragmas, logConfig) {
			lc = createLogContext({ log: logConfig }, { worker: "write-worker" });
			db = new Database(lc, dbPath);
			applyPragmas(db, pragmas);
			runner = new StatementRunner(db);
			mode = cpMode;
			createProcessor();
		},
		getSubscriptionState() {
			return getSubscriptionState(must(runner));
		},
		processMessage(downstream) {
			return must(processor).processMessage(must(lc), downstream);
		},
		abort() {
			must(processor).abort(must(lc));
			createProcessor();
		},
		stop() {
			db?.close();
			db = void 0;
			runner = void 0;
			processor = void 0;
		}
	};
}
var api = createAPI();
port.on("message", (msg) => {
	try {
		const result = api[msg.method](...msg.args);
		if (msg.method !== "abort") port.postMessage({
			method: msg.method,
			result
		});
	} catch (e) {
		if (msg.method !== "abort") port.postMessage({
			method: msg.method,
			error: e
		});
	}
});
//#endregion
export {};

//# sourceMappingURL=write-worker.js.map