/**
 * Singleton initialization for libsodium-wrappers
 * 
 * Ensures libsodium.wasm is loaded exactly once and provides
 * safe async access to the initialized instance.
 */

import sodium from 'libsodium-wrappers'

let sodiumInstance: typeof sodium | null = null

/**
 * Get initialized sodium instance
 * Safe to call multiple times - initialization happens only once
 * 
 * @returns Promise that resolves to initialized sodium
 * @throws Error if sodium initialization fails
 */
export async function getSodium() {
  if (!sodiumInstance) {
    await sodium.ready
    sodiumInstance = sodium

    if (!sodiumInstance.to_base64) {
      throw new Error(
        'Libsodium initialization failed: wasm functions missing'
      )
    }
  }

  return sodiumInstance
}

/**
 * Synchronous check if sodium is ready (after first getSodium call)
 */
export function isSodiumReady(): boolean {
  return sodiumInstance !== null
}
