import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';
import { SECURE_KEY_NAME, ENCRYPTION_KEY_BYTES } from './config';

function generateHexKey(bytes: number): string {
  const arr = new Uint8Array(bytes);
  globalThis.crypto.getRandomValues(arr);
  return Array.from(arr, b => b.toString(16).padStart(2, '0')).join('');
}

/**
 * Returns the device's local-mode database encryption key (TOKEN_ENCRYPTION_KEY),
 * generating and persisting one in secure storage (Android Keystore / iOS Keychain)
 * on first launch. Throws if secure storage is unavailable — the caller
 * (LoadingScreen) surfaces that rather than starting the server with no key.
 */
export async function getOrCreateEncryptionKey(): Promise<string> {
  try {
    const { value } = await SecureStoragePlugin.get({ key: SECURE_KEY_NAME });
    if (value) return value;
  } catch {
    // Not found — fall through to generate one.
  }

  const key = generateHexKey(ENCRYPTION_KEY_BYTES);
  try {
    await SecureStoragePlugin.set({ key: SECURE_KEY_NAME, value: key });
  } catch (err) {
    throw new Error('Failed to persist the encryption key to secure storage: ' + String(err));
  }
  return key;
}
