import { getSecureStorage } from '../storage/SecureStorage.js';

/**
 * Key Manager - Manages user encryption keys using OS-level secure storage
 * - macOS: Keychain
 * - Windows: DPAPI
 * - Linux: gnome-libsecret/kwallet
 */

/**
 * Get user encryption key from secure storage
 * @param userId - User ID
 * @returns User's encryption key
 * @throws Error if encryption key not found
 */
export function getUserEncryptionKey(userId: string): string {
    const storage = getSecureStorage();
    const key = storage.get<string>(`encryptionKey-${userId}`);
    if (key === null || key === undefined) {
        throw new Error(`Unknown encryptionKey`);
    }
    return key;
}

/**
 * Set user encryption key in secure storage (OS-encrypted)
 * @param userId - User ID
 * @param encryptionKey - Encryption key to store
 */
export function setUserEncryptionKey(userId: string, encryptionKey: string): void {
    const storage = getSecureStorage();
    storage.set(`encryptionKey-${userId}`, encryptionKey);
}

/**
 * Check if user has an encryption key
 * @param userId - User ID
 * @returns True if key exists
 */
export function hasUserEncryptionKey(userId: string): boolean {
    const storage = getSecureStorage();
    return storage.has(`encryptionKey-${userId}`);
}

/**
 * Delete user encryption key
 * @param userId - User ID
 */
export function deleteUserEncryptionKey(userId: string): void {
    const storage = getSecureStorage();
    storage.delete(`encryptionKey-${userId}`);
}
