/**
 * Catalogue of known settings keys with their kind (plain vs. encrypted).
 *
 * Adding a new setting? Add it here so the Settings UI knows how to render it
 * (textarea vs. password input) and so `getSecret`/`setSecret` route to the
 * correct serialization.
 */

export type SettingKind = 'plain' | 'secret';

export interface SettingDefinition {
  key: string;
  kind: SettingKind;
  /** Optional fallback env-var read if DB value is empty. */
  envFallback?: string;
  /** Free-form description shown next to the input in the Settings UI. */
  description?: string;
}

export const SETTINGS_CATALOGUE = {
  // ---- Secrets ----------------------------------------------------------------
  openrouter_api_key: {
    key: 'openrouter_api_key',
    kind: 'secret',
    envFallback: 'OPENROUTER_API_KEY',
    description: 'OpenRouter API key for LLM calls (Claude Sonnet by default).',
  },
  fal_api_key: {
    key: 'fal_api_key',
    kind: 'secret',
    envFallback: 'FAL_KEY',
    description: 'fal.ai API key for hero-image generation.',
  },
  send_provider_config: {
    key: 'send_provider_config',
    kind: 'secret',
    envFallback: 'SEND_PROVIDER_CONFIG',
    description:
      'JSON für den aktiven SendProvider. SMTP: { "kind":"smtp", "host", "port", … }. Microsoft Graph: { "kind":"m365", "tenantId", "clientId", "clientSecret", "auditBcc?" } — alternativ gleiche Werte als Env M365_* oder SEND_PROVIDER_CONFIG (eine Zeile JSON, z. B. für den Worker).',
  },
  crm_adapter_config: {
    key: 'crm_adapter_config',
    kind: 'secret',
    description:
      'JSON for the active CrmAdapter (generic-rest: baseUrl/auth/endpoints; cumas: username/password).',
  },

  // ---- Plain settings (no encryption needed) ----------------------------------
  system_prompt_generate: {
    key: 'system_prompt_generate',
    kind: 'plain',
    description: 'Master system prompt for the produce_email LLM call.',
  },
  system_prompt_suggest: {
    key: 'system_prompt_suggest',
    kind: 'plain',
    description: 'System prompt for the briefing-suggestion extractor.',
  },
  system_prompt_image: {
    key: 'system_prompt_image',
    kind: 'plain',
    description: 'Style/tone instructions appended to hero-image prompts.',
  },
  conversion_polling: {
    key: 'conversion_polling',
    kind: 'plain',
    description: 'CRM-poll cadence (intervalMinutes) and field-mapping config.',
  },
} as const satisfies Record<string, SettingDefinition>;

export type KnownSettingKey = keyof typeof SETTINGS_CATALOGUE;

export function isSecretKey(key: string): boolean {
  const def = (SETTINGS_CATALOGUE as Record<string, SettingDefinition>)[key];
  return def?.kind === 'secret';
}

export function getEnvFallback(key: string): string | undefined {
  const def = (SETTINGS_CATALOGUE as Record<string, SettingDefinition>)[key];
  if (!def?.envFallback) return undefined;
  return process.env[def.envFallback]?.trim() || undefined;
}
