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

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

/** Bearer token comes from httpOnly session cookies — never trust localStorage cache. */
export async function ensureAccessToken(): Promise<string | null> {
  if (!syncPromise) {
    syncPromise = (async () => {
      const data = await fetchSession()
      if (data && applySessionToStore(data)) {
        return useAuthStore.getState().accessToken
      }
      useAuthStore.getState().logout()
      return null
    })().finally(() => {
      syncPromise = null
    })
  }
  return syncPromise
}
