// `KeyStore` and `Cache` are the platform-agnostic persistence
// boundaries every Galaxy UI build target (web, Wails desktop,
// Capacitor mobile) must satisfy. The web implementation in this
// directory backs them with WebCrypto non-exportable Ed25519 keys
// and IndexedDB; later phases plug Wails Keychain / Capacitor
// Preferences and SQLite behind the same interfaces without touching
// the orchestration layer.
//
// Public signatures intentionally use only `Uint8Array`, `string`,
// and `unknown` — no `CryptoKey`, no `IDBDatabase`, no `idb` symbols
// — so callers stay portable across platforms. The `Signer` type from
// `api/galaxy-client.ts` is structurally compatible with
// `DeviceKeypair.sign`: the constructor takes
// `signer: keypair.sign.bind(keypair)` (or an arrow wrapper).

/**
 * DeviceKeypair is the load-or-generate output of a [KeyStore]: the
 * raw 32-byte Ed25519 public key in `publicKey`, and a `sign` method
 * that produces the raw 64-byte Ed25519 signature for the given
 * canonical bytes. The private key never leaves the platform's secure
 * storage.
 */
export interface DeviceKeypair {
	readonly publicKey: Uint8Array;
	sign(canonicalBytes: Uint8Array): Promise<Uint8Array>;
}

/**
 * KeyStore persists exactly one device keypair at a time. `load`
 * returns `null` when no keypair has been generated yet; `generate`
 * always overwrites any prior keypair with a fresh one; `clear`
 * deletes the stored keypair so the next `load` returns `null`.
 */
export interface KeyStore {
	load(): Promise<DeviceKeypair | null>;
	generate(): Promise<DeviceKeypair>;
	clear(): Promise<void>;
}

/**
 * Cache is a generic local key-value store partitioned by namespace.
 * Values flow through the platform's structured-clone equivalent, so
 * `Uint8Array`, plain objects, nested arrays, and primitives all
 * round-trip. `clear()` without a namespace wipes every entry; with
 * a namespace it wipes only that namespace's keys.
 */
export interface Cache {
	get<T = unknown>(namespace: string, key: string): Promise<T | undefined>;
	put<T = unknown>(namespace: string, key: string, value: T): Promise<void>;
	delete(namespace: string, key: string): Promise<void>;
	clear(namespace?: string): Promise<void>;
}

export interface Store {
	keyStore: KeyStore;
	cache: Cache;
}

export type StoreLoader = () => Promise<Store>;

import { loadWebStore } from "./web";

/**
 * loadStore resolves the [Store] implementation appropriate for the
 * current build target. Phase 6 ships only the web adapter; later
 * phases plug `WailsStore` and `CapacitorStore` here behind a
 * build-time selector.
 */
export const loadStore: StoreLoader = loadWebStore;
