/** Encrypted vault and OS-protected (biometric) unlocking. Secrets never leave the Rust Core. */
import { call } from "../transport";
import type { BiometricStatus, Result, VaultStatus } from "../types";

async function unwrap<T>(command: string, channel: string): Promise<T> {
  const result = await call<Result<T>>(command, channel);
  if (!result.ok) throw Object.assign(new Error(result.error.message), { code: result.error.code });
  return result.value;
}

export const vault = Object.freeze({
  status: () => call<VaultStatus>("core_vault_status", "vault:status"),
  create: (password: string) => call<VaultStatus>("core_vault_create", "vault:create", { password }),
  unlock: (password: string) => call<VaultStatus>("core_vault_unlock", "vault:unlock", { password }),
  lock: () => call<VaultStatus>("core_vault_lock", "vault:lock"),
  reset: (confirmation: string) => call<VaultStatus>("core_vault_reset", "vault:reset", { confirmation })
});

export const biometrics = Object.freeze({
  status: () => unwrap<BiometricStatus>("core_biometrics_status", "biometrics:status"),
  enable: () => unwrap<BiometricStatus>("core_biometrics_enable", "biometrics:enable"),
  disable: () => unwrap<{ enabled: false; enrolled: false }>("core_biometrics_disable", "biometrics:disable"),
  unlock: () => unwrap<VaultStatus>("core_biometrics_unlock", "biometrics:unlock"),
  autoUnlock: () => unwrap<{ attempted: boolean; reason?: string; status?: VaultStatus; error?: { code: string } }>("core_biometrics_auto_unlock", "biometrics:autoUnlock"),
  authenticate: () => unwrap<{ authenticated: true }>("core_biometrics_authenticate", "biometrics:authenticate")
});

export const keychain = (action: string, options: Record<string, unknown> = {}) => call<Record<string, unknown>>("core_keychain", "keychain", { ...options, action });
