/**
 * JS facade over the `ulti-core` secure store Tauri commands. The store is
 * shared across the suite (cross-app SSO) so the session written by one app is
 * readable by the others.
 */
import { invoke } from "@/lib/native/bridge"
import { isTauriRuntime } from "@/lib/platform"

const KEY_SESSION = "session"
const KEY_CONFIG = "runtime_config"
const KEY_PUSH = "push_token"

/**
 * Fallback for a mobile build opened in a plain browser (dev): persist to
 * localStorage so the native flow can be exercised without a device.
 */
function localFallback() {
  return typeof window !== "undefined" ? window.localStorage : null
}

async function set(key: string, value: string): Promise<void> {
  if (isTauriRuntime()) {
    await invoke("plugin:ulti-core|store_set", { key, value })
    return
  }
  localFallback()?.setItem(`ulti-secure:${key}`, value)
}

async function get(key: string): Promise<string | null> {
  if (isTauriRuntime()) {
    return (await invoke<string | null>("plugin:ulti-core|store_get", { key })) ?? null
  }
  return localFallback()?.getItem(`ulti-secure:${key}`) ?? null
}

async function del(key: string): Promise<void> {
  if (isTauriRuntime()) {
    await invoke("plugin:ulti-core|store_delete", { key })
    return
  }
  localFallback()?.removeItem(`ulti-secure:${key}`)
}

export type NativeSession = {
  accessToken: string
  refreshToken: string | null
  expiresAt: number
  user: unknown | null
}

export async function readSession(): Promise<NativeSession | null> {
  const raw = await get(KEY_SESSION)
  if (!raw) return null
  try {
    return JSON.parse(raw) as NativeSession
  } catch {
    return null
  }
}

export async function writeSession(session: NativeSession): Promise<void> {
  await set(KEY_SESSION, JSON.stringify(session))
}

export async function clearSession(): Promise<void> {
  if (isTauriRuntime()) {
    await invoke("plugin:ulti-core|store_clear")
    return
  }
  await del(KEY_SESSION)
}

export async function readStoredConfig(): Promise<string | null> {
  return get(KEY_CONFIG)
}

export async function writeStoredConfig(json: string): Promise<void> {
  await set(KEY_CONFIG, json)
}

export async function readPushToken(): Promise<string | null> {
  return get(KEY_PUSH)
}

export async function writePushToken(token: string): Promise<void> {
  await set(KEY_PUSH, token)
}
