import { buildDefaultCorsOrigins } from "../gateway/host.js";
import { isNetworkAccessibleBindHost, resolveGatewayBindMode, resolveGatewayEffectiveHost } from "../config/gateway-bind.js";
import { enumerateLanGatewayCandidates } from "./tunnel-qr.js";
import { assertGatewayAuthConfigured, resolveGatewayAuth } from "../gateway/auth.js";
import { assertGatewayRuntimeConfig } from "../gateway/runtime-config.js";
//#region src/tunnel/enable-lan-pairing.ts
function mergeCorsOriginsForLan(config, port, bindHost) {
	if (!config.gateway) return;
	const existing = new Set((config.gateway.corsOrigins ?? []).map((o) => o.trim()).filter(Boolean));
	for (const origin of buildDefaultCorsOrigins({
		port,
		bindHost
	})) existing.add(origin);
	for (const candidate of enumerateLanGatewayCandidates(port)) existing.add(candidate.url);
	config.gateway.corsOrigins = [...existing];
}
function applyLanPairingGatewayPatch(config) {
	const bindMode = resolveGatewayBindMode(config);
	const listenHost = resolveGatewayEffectiveHost(config);
	if (bindMode === "lan" && isNetworkAccessibleBindHost(listenHost)) return {
		ok: true,
		changed: false
	};
	if (!config.gateway) return {
		ok: false,
		message: "Gateway section missing from config"
	};
	config.gateway.bind = "lan";
	delete config.gateway.customBindHost;
	const port = config.gateway.port ?? 18790;
	mergeCorsOriginsForLan(config, port, resolveGatewayEffectiveHost(config));
	try {
		const auth = resolveGatewayAuth({ authConfig: config.gateway.auth });
		assertGatewayAuthConfigured(auth);
		assertGatewayRuntimeConfig({
			cfg: config,
			auth,
			port
		});
	} catch (err) {
		return {
			ok: false,
			message: err instanceof Error ? err.message : String(err)
		};
	}
	return {
		ok: true,
		changed: true
	};
}
//#endregion
export { applyLanPairingGatewayPatch };

//# sourceMappingURL=enable-lan-pairing.js.map