/**
 * API-key resolver helpers — single source of truth for "where does the
 * OpenRouter / fal.ai key come from at runtime".
 *
 * Lookup order:
 *   1. Encrypted Settings DB (`getSecret`)
 *   2. Env-var fallback (declared in keys.ts catalogue)
 *
 * Throws if neither is configured AND the caller declared the key as required.
 * Returns undefined for soft-optional lookups (caller can render a banner).
 */

import { getSecret } from './repo';

class MissingApiKeyError extends Error {
  constructor(human: string) {
    super(human);
    this.name = 'MissingApiKeyError';
  }
}

/**
 * Get the OpenRouter API key (used by all AI/LLM endpoints).
 * Throws if missing — every AI call needs a key.
 */
export function getOpenRouterKey(): string {
  const key = getSecret('openrouter_api_key');
  if (!key) {
    throw new MissingApiKeyError(
      'OpenRouter API key not configured. Set it in Settings UI or via OPENROUTER_API_KEY env-var.',
    );
  }
  return key;
}

/**
 * Get the OpenRouter key, or undefined if missing. Use this for UI features
 * that should hide instead of error when the key isn't set.
 */
export function getOpenRouterKeyOptional(): string | undefined {
  return getSecret('openrouter_api_key');
}

/**
 * Get the fal.ai API key (used by hero-image generation).
 * Returns undefined if missing — hero-image generation is optional; callers
 * fall back to a stub or skip the feature.
 */
export function getFalKey(): string | undefined {
  return getSecret('fal_api_key');
}
