import { useAuthStore } from "@/lib/api/auth-store"
import { fetchSession, applySessionToStore } from "@/lib/auth/session-sync"
import { useNativeRuntime } from "@/lib/platform"
import { ensureNativeAccessToken } from "@/lib/auth/native-session"

let syncPromise: Promise<string | null> | null = null

/**
 * Resolve the current bearer token.
 * - Web: from the httpOnly session cookies (via `/api/auth/session`).
 * - Native (Tauri): from the OS secure store, refreshing against Authentik.
 */
export async function ensureAccessToken(): Promise<string | null> {
  if (!syncPromise) {
    syncPromise = (async () => {
      if (useNativeRuntime()) {
        return ensureNativeAccessToken()
      }
      const data = await fetchSession()
      if (data && applySessionToStore(data)) {
        return useAuthStore.getState().accessToken
      }
      useAuthStore.getState().logout()
      return null
    })().finally(() => {
      syncPromise = null
    })
  }
  return syncPromise
}
