/**
 * API Key Storage Utilities
 *
 * localStorage utilities for persisting API keys
 */

import { API_KEY_STORAGE_KEY } from './constants';

/**
 * Check if localStorage is available (browser environment)
 */
function isLocalStorageAvailable(): boolean {
  try {
    return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
  } catch {
    return false;
  }
}

/**
 * Get stored API key from localStorage
 *
 * @returns The stored API key or null if not found
 */
export function getStoredKey(): string | null {
  if (!isLocalStorageAvailable()) {
    return null;
  }

  try {
    return localStorage.getItem(API_KEY_STORAGE_KEY);
  } catch (error) {
    console.error('Error reading API key from localStorage:', error);
    return null;
  }
}

/**
 * Save API key to localStorage
 *
 * @param apiKey - The API key to store
 */
export function setStoredKey(apiKey: string): void {
  if (!isLocalStorageAvailable()) {
    console.warn('localStorage is not available');
    return;
  }

  try {
    localStorage.setItem(API_KEY_STORAGE_KEY, apiKey);
  } catch (error) {
    console.error('Error saving API key to localStorage:', error);
  }
}

/**
 * Remove API key from localStorage
 */
export function clearStoredKey(): void {
  if (!isLocalStorageAvailable()) {
    return;
  }

  try {
    localStorage.removeItem(API_KEY_STORAGE_KEY);
  } catch (error) {
    console.error('Error removing API key from localStorage:', error);
  }
}
