import { unreachable } from "../../../../shared/src/asserts.js";
import { must } from "../../../../shared/src/must.js";
import { Database } from "../../../../zqlite/src/db.js";
import { getServerVersion, isAdminPasswordValid } from "../../config/zero-config.js";
import { StatementRunner } from "../../db/statements.js";
import { loadPermissions } from "../../auth/load-permissions.js";
import { _usingCtx } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/usingCtx.js";
import { analyzeQuery } from "../analyze.js";
//#region ../zero-cache/src/services/view-syncer/inspect-handler.ts
async function handleInspect(lc, body, cvr, client, inspectorDelegate, clientGroupID, cvrStore, config, ctx) {
	if (body.op !== "authenticate" && !inspectorDelegate.isAuthenticated(clientGroupID)) {
		lc.info?.("Client not authenticated to access the inspector protocol. Sending authentication challenge");
		client.sendInspectResponse(lc, {
			op: "authenticated",
			id: body.id,
			value: false
		});
		return;
	}
	try {
		switch (body.op) {
			case "queries": {
				const enhancedRows = (await cvrStore.inspectQueries(lc, cvr.ttlClock, body.clientID)).map((row) => ({
					...row,
					ast: row.ast ?? inspectorDelegate.getASTForQuery(row.queryID) ?? null,
					metrics: inspectorDelegate.getMetricsJSONForQuery(row.queryID)
				}));
				client.sendInspectResponse(lc, {
					op: "queries",
					id: body.id,
					value: enhancedRows
				});
				break;
			}
			case "metrics":
				client.sendInspectResponse(lc, {
					op: "metrics",
					id: body.id,
					value: inspectorDelegate.getMetricsJSON()
				});
				break;
			case "version":
				client.sendInspectResponse(lc, {
					op: "version",
					id: body.id,
					value: getServerVersion(config)
				});
				break;
			case "authenticate": {
				const password = body.value;
				const ok = isAdminPasswordValid(lc, config, password);
				if (ok) inspectorDelegate.setAuthenticated(clientGroupID);
				else inspectorDelegate.clearAuthenticated(clientGroupID);
				client.sendInspectResponse(lc, {
					op: "authenticated",
					id: body.id,
					value: ok
				});
				break;
			}
			case "analyze-query": {
				let ast = body.ast ?? body.value;
				let legacyQuery = true;
				if (body.name && body.args) {
					ast = await inspectorDelegate.transformCustomQuery(body.name, body.args, ctx);
					legacyQuery = false;
				}
				if (ast === void 0) throw new Error("AST is required for analyze-query operation. Either provide an AST directly or ensure custom query transformation is configured.");
				let permissions;
				if (legacyQuery) try {
					var _usingCtx$1 = _usingCtx();
					const loaded = loadPermissions(lc, new StatementRunner(_usingCtx$1.u(new Database(lc, config.replica.file))), config.app.id, config);
					if (loaded.permissions) permissions = loaded.permissions;
					else lc.info?.("No permissions loaded; analyze-query will run without applying permissions.");
				} catch (_) {
					_usingCtx$1.e = _;
				} finally {
					_usingCtx$1.d();
				}
				const result = await analyzeQuery(lc, config, must(cvr.clientSchema), ast, body.options?.syncedRows, body.options?.vendedRows, permissions, ctx.auth?.type === "jwt" ? ctx.auth : void 0, body.options?.joinPlans);
				client.sendInspectResponse(lc, {
					op: "analyze-query",
					id: body.id,
					value: result
				});
				break;
			}
			default: unreachable(body);
		}
	} catch (e) {
		lc.error?.("Error handling inspect message", e);
		client.sendInspectResponse(lc, {
			op: "error",
			id: body.id,
			value: e.message
		});
	}
}
//#endregion
export { handleInspect };

//# sourceMappingURL=inspect-handler.js.map