import { safeStorage } from 'electron';
import { getStore } from '../store';

/**
 * Token storage with two-tier fallback:
 *  1. Electron safeStorage + electron-store (encrypted at rest)
 *  2. Plain electron-store (last resort — e.g. WSL with no keyring)
 */

function canUseSafeStorage(): boolean {
  try {
    return safeStorage.isEncryptionAvailable();
  } catch {
    return false;
  }
}

// --- electron-store helpers (with optional safeStorage encryption) ---

function readFromStore(providerName: string): string | null {
  const tokens = getStore().get('encryptedTokens');
  const stored = tokens[providerName];
  if (!stored) return null;

  if (canUseSafeStorage()) {
    try {
      return safeStorage.decryptString(Buffer.from(stored, 'base64'));
    } catch {
      // Stored value might be plaintext from a previous fallback
      return stored;
    }
  }
  // No encryption available — value is stored as plaintext
  return stored;
}

function writeToStore(providerName: string, token: string): void {
  let value: string;
  if (canUseSafeStorage()) {
    value = safeStorage.encryptString(token).toString('base64');
  } else {
    // Last resort: store plaintext (WSL with no keyring)
    value = token;
  }
  const tokens = getStore().get('encryptedTokens');
  getStore().set('encryptedTokens', { ...tokens, [providerName]: value });
}

function removeFromStore(providerName: string): void {
  const tokens = getStore().get('encryptedTokens');
  const { [providerName]: _, ...rest } = tokens;
  getStore().set('encryptedTokens', rest);
}

// --- public API ---

/** Read a stored token for the given provider. */
export async function getToken(providerName: string): Promise<string | null> {
  return readFromStore(providerName);
}

/** Store a token for the given provider. */
export async function setToken(providerName: string, token: string): Promise<void> {
  writeToStore(providerName, token);
}

/** Delete a stored token for the given provider. */
export async function deleteToken(providerName: string): Promise<boolean> {
  removeFromStore(providerName);
  return true;
}
