const API_BASE = (import.meta.env.VITE_API_BASE ?? "").trim().replace(/\/$/, "");

/** Resolve an API path. Empty base keeps same-origin relative paths for web `dist/`. */
export function apiUrl(path: string): string {
	if (!path.startsWith("/")) {
		throw new Error(`API path must start with /: ${path}`);
	}
	return API_BASE ? `${API_BASE}${path}` : path;
}

export function getApiBase(): string {
	return API_BASE;
}

/** Resolve a WebSocket URL for an API path. */
export function wsUrl(path: string): string {
	const httpPath = apiUrl(path);
	if (httpPath.startsWith("https://")) {
		return `wss://${httpPath.slice("https://".length)}`;
	}
	if (httpPath.startsWith("http://")) {
		return `ws://${httpPath.slice("http://".length)}`;
	}
	const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
	return `${protocol}//${window.location.host}${httpPath}`;
}
