import { writable, get } from "svelte/store";

const _password = writable<string | null>(null);
const _unlocked = writable(false);

export const vaultUnlocked = { subscribe: _unlocked.subscribe };

export function isVaultReady(): boolean {
  return get(_unlocked);
}

export function getSessionPassword(): string | null {
  return get(_password);
}

export function setVaultSession(password: string): void {
  _password.set(password);
  _unlocked.set(true);
}

export function clearVaultSession(): void {
  _password.set(null);
  _unlocked.set(false);
}

let _flushCallback: (() => Promise<void>) | null = null;

export function setFlushCallback(fn: () => Promise<void>): void {
  _flushCallback = fn;
}

export async function flushBeforeClose(): Promise<void> {
  if (_flushCallback) await _flushCallback();
}
