import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

const KEY_NAME = 'tokenEncryptionKey';
const KEY_BYTES = 48;

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.
 */
export async function getOrCreateEncryptionKey(): Promise<string> {
  try {
    const { value } = await SecureStoragePlugin.get({ key: KEY_NAME });
    if (value) return value;
  } catch {
    // Not found — fall through to generate one.
  }

  const key = generateHexKey(KEY_BYTES);
  await SecureStoragePlugin.set({ key: KEY_NAME, value: key });
  return key;
}
