/**
 * Persistent settings via Tauri store plugin.
 * Stores key-value data in a JSON file managed by the Tauri backend.
 * Falls back to in-memory Map when running in browser (dev mode).
 */
import { Store } from "@tauri-apps/plugin-store"

let _store: Store | null = null
const memoryStore = new Map<string, unknown>()

function isTauri(): boolean {
  return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window
}

async function getStore(): Promise<Store> {
  if (!_store) {
    _store = isTauri() ? await Store.load("settings.json") : null
  }
  return _store as Store
}

export function useSettings() {
  async function get<T>(key: string): Promise<T | undefined> {
    if (isTauri()) {
      const store = await getStore()
      return await store.get<T>(key)
    }
    return memoryStore.get(key) as T | undefined
  }

  async function set<T>(key: string, value: T): Promise<void> {
    if (isTauri()) {
      const store = await getStore()
      await store.set(key, value)
      await store.save()
      return
    }
    memoryStore.set(key, value)
  }

  async function getRecentWorkspaces(): Promise<string[]> {
    return (await get<string[]>("recentWorkspaces")) ?? []
  }

  async function addRecentWorkspace(path: string): Promise<void> {
    const recents = await getRecentWorkspaces()
    const filtered = recents.filter((p) => p !== path)
    filtered.unshift(path)
    await set("recentWorkspaces", filtered.slice(0, 10))
  }

  /**
   * Returns the configured pages directory relative to the workspace root.
   * Controls where new page files are created when navigating to a `[[link]]`
   * that doesn't exist yet. The default `"pages"` matches the workspace layout
   * created by `ensureDirectories()` in the workspace store.
   *
   * This setting only affects **creation**, not **recognition** — the indexer
   * always walks the entire workspace regardless of this value.
   */
  async function getPagesDir(): Promise<string> {
    return (await get<string>("pagesDir")) ?? "pages"
  }

  return { get, set, getRecentWorkspaces, addRecentWorkspace, getPagesDir }
}
