type TauriWindowHandle = {
  close: () => Promise<void>
  isMaximized: () => Promise<boolean>
  maximize: () => Promise<void>
  minimize: () => Promise<void>
  unmaximize: () => Promise<void>
}

declare global {
  interface Window {
    __TAURI_INTERNALS__?: unknown
  }
}

function isTauriRuntime(): boolean {
  if (typeof window === "undefined") {
    return false
  }

  return "__TAURI_INTERNALS__" in window
}

async function getCurrentWindowHandle(): Promise<TauriWindowHandle | null> {
  if (!isTauriRuntime()) {
    return null
  }

  const tauriWindow = await import("@tauri-apps/api/window")
  return tauriWindow.getCurrentWindow()
}

export function isDesktopRuntime(): boolean {
  return isTauriRuntime()
}

export function getDragRegionProps(): Record<string, string> {
  return isDesktopRuntime() ? { "data-tauri-drag-region": "" } : {}
}

export async function minimizeWindow(): Promise<void> {
  const currentWindow = await getCurrentWindowHandle()
  if (!currentWindow) {
    return
  }

  await currentWindow.minimize()
}

export async function toggleMaximizeWindow(): Promise<void> {
  const currentWindow = await getCurrentWindowHandle()
  if (!currentWindow) {
    return
  }

  if (await currentWindow.isMaximized()) {
    await currentWindow.unmaximize()
    return
  }

  await currentWindow.maximize()
}

export async function closeWindow(): Promise<void> {
  const currentWindow = await getCurrentWindowHandle()
  if (!currentWindow) {
    return
  }

  await currentWindow.close()
}
