/**
 * Device-specific backup encryption key.
 *
 * Generated randomly (256-bit) on first call and persisted via the same
 * safeStorage + electron-store mechanism used for auth tokens (see token.ts).
 * This key is device-bound — it never leaves the machine and is not derived
 * from the user's password, so social-login users can use backups without issue.
 *
 * Usage:
 *   const key = await getBackupKey();  // Buffer of 32 bytes
 */

import { randomBytes } from 'crypto';
import { getToken, setToken } from '../ai/token';

const BACKUP_KEY_STORE_NAME = 'backup_key';

/**
 * Return the device-specific backup encryption key (32 bytes).
 *
 * Generates a fresh key on first call and stores it via safeStorage so it
 * survives app restarts.  Subsequent calls return the same key.
 */
export async function getBackupKey(): Promise<Buffer> {
  const stored = await getToken(BACKUP_KEY_STORE_NAME);

  if (stored) {
    return Buffer.from(stored, 'base64');
  }

  // First launch: generate a random 256-bit key and persist it.
  const key = randomBytes(32);
  await setToken(BACKUP_KEY_STORE_NAME, key.toString('base64'));
  return key;
}

/**
 * Delete the stored backup key (e.g. on device-wipe / factory reset).
 * After this call, the next `getBackupKey()` will generate a new key —
 * any backups encrypted with the old key will be unrecoverable.
 */
export async function deleteBackupKey(): Promise<void> {
  const { deleteToken } = await import('../ai/token');
  await deleteToken(BACKUP_KEY_STORE_NAME);
}
