/**
 * Inter-app launching: open a sibling suite app at a given route via its custom
 * scheme (e.g. UltiMail opening `ultidrive://go/drive/...`). Falls back to the
 * web route in a plain browser.
 */
import { invoke } from "@/lib/native/bridge"
import { appScheme, isTauriRuntime, type SuiteApp } from "@/lib/platform"

/** Build the deep link that opens `app` at `route`. */
export function siblingDeepLink(app: SuiteApp, route: string): string {
  const clean = route.startsWith("/") ? route.slice(1) : route
  return `${appScheme(app)}://go/${clean}`
}

/** Open a sibling app at a route (deep link). On web, navigate in-page. */
export async function openSiblingApp(app: SuiteApp, route: string): Promise<void> {
  const link = siblingDeepLink(app, route)
  if (isTauriRuntime()) {
    try {
      const opener = await import("@tauri-apps/plugin-opener")
      await opener.openUrl(link)
      return
    } catch {
      await invoke("plugin:ulti-core|app_open_url", { url: link })
      return
    }
  }
  if (typeof window !== "undefined") {
    window.location.href = route
  }
}
