import { i as formatErrorMessage } from "./errors-Ca_eBjrO.js";
import { i as enableTailscaleServe, n as disableTailscaleServe, o as getTailnetHostname, r as enableTailscaleFunnel, s as hasTailscaleFunnelRouteForPort, t as disableTailscaleFunnel } from "./tailscale-DCF5q8Mb.js";
import { n as resolveTailscalePublishedHost } from "./tailscale-status-B3whvNX4.js";
//#region src/gateway/server-tailscale.ts
async function startGatewayTailscaleExposure(params) {
	if (params.tailscaleMode === "off") return null;
	const serviceName = params.tailscaleMode === "serve" ? params.serviceName?.trim() || void 0 : void 0;
	try {
		if (params.tailscaleMode === "serve") {
			if (params.preserveFunnel === true) {
				if (await hasTailscaleFunnelRouteForPort(params.port)) {
					const resetSuffix = params.resetOnExit ? "; resetOnExit is a no-op because no Serve route was applied this run" : "";
					params.logTailscale.info(`serve skipped: preserving externally configured Tailscale Funnel for port ${params.port}${resetSuffix}`);
					return null;
				}
			}
			if (serviceName) await enableTailscaleServe(params.port, void 0, serviceName);
			else await enableTailscaleServe(params.port);
		} else await enableTailscaleFunnel(params.port);
		const host = await getTailnetHostname().catch(() => null);
		if (host) {
			const uiPath = params.controlUiBasePath ? `${params.controlUiBasePath}/` : "/";
			const publicHost = resolveTailscalePublishedHost({
				tailscaleMode: params.tailscaleMode,
				tailnetHost: host,
				serviceName
			});
			if (publicHost) {
				const serviceLabel = serviceName ? ` for ${serviceName}` : "";
				params.logTailscale.info(`${params.tailscaleMode} enabled${serviceLabel}: https://${publicHost}${uiPath} (WS via wss://${publicHost})`);
			} else params.logTailscale.info(`${params.tailscaleMode} enabled`);
		} else params.logTailscale.info(`${params.tailscaleMode} enabled`);
	} catch (err) {
		params.logTailscale.warn(`${params.tailscaleMode} failed: ${formatErrorMessage(err)}`);
	}
	if (!params.resetOnExit) return null;
	return async () => {
		try {
			if (params.tailscaleMode === "serve") if (serviceName) await disableTailscaleServe(void 0, serviceName);
			else await disableTailscaleServe();
			else await disableTailscaleFunnel();
		} catch (err) {
			params.logTailscale.warn(`${params.tailscaleMode} cleanup failed: ${formatErrorMessage(err)}`);
		}
	};
}
//#endregion
export { startGatewayTailscaleExposure };
