/**
 * Persist/hydrate the selected backend (runtime config) through the shared OS
 * secure store so the choice is part of cross-app SSO: pick a server in one app
 * and the siblings inherit it.
 */
import {
  getRuntimeConfig,
  setRuntimeConfig,
  type RuntimeConfig,
} from "@/lib/runtime-config"
import { readStoredConfig, writeStoredConfig } from "@/lib/native/secure-store"

export async function persistNativeRuntimeConfig(cfg: RuntimeConfig): Promise<void> {
  setRuntimeConfig(cfg)
  try {
    await writeStoredConfig(JSON.stringify(cfg))
  } catch {
    /* secure store unavailable in dev browser — localStorage fallback applies */
  }
}

/** Load the runtime config from the secure store into memory if not already set. */
export async function hydrateNativeRuntimeConfig(): Promise<RuntimeConfig | null> {
  if (getRuntimeConfig()) return getRuntimeConfig()
  try {
    const raw = await readStoredConfig()
    if (raw) {
      const cfg = JSON.parse(raw) as RuntimeConfig
      setRuntimeConfig(cfg)
      return cfg
    }
  } catch {
    /* ignore */
  }
  return null
}
