/**
 * GET /api/help — searchable index for the Help Center + smart search.
 *
 * Returns:
 *   - articles: HELP_ARTICLE_META (metadata only; bodies served by /help/<slug>)
 *   - actions:  per-setting-action CURRENT state
 *       • secret kind     → { status: 'set' | 'unset' }   (NEVER the value)
 *       • config kind      → { value: <current config value> }
 *       • trust-mode kind  → { value: <current mode> }
 *
 * Security: secret values are never read or returned here. Only presence/status.
 * Reads only — no auth gate (mirrors GET /api/config). All writes go through the
 * individual admin-gated, audited endpoints referenced by resolveWrite().
 */

import { SETTING_ACTIONS, HELP_ARTICLE_META } from '@/lib/help/registry.js';
import { listSecrets } from '@/lib/secrets.js';
import { getModel, getDesignStyle } from '@/lib/agent-config.js';
import { getMainAgentTrustMode } from '@/lib/tools/registry.js';
import { requireSession, getAuthMode } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

function resolveCurrent(action, secretNames) {
  switch (action.kind) {
    case 'secret':
      return { status: secretNames.has(action.secretName) ? 'set' : 'unset' };
    case 'config':
      if (action.configKey === 'model') return { value: getModel() };
      if (action.configKey === 'designStyle') return { value: getDesignStyle() };
      return {};
    case 'trust-mode':
      return { value: getMainAgentTrustMode() };
    default:
      return {};
  }
}

export async function GET(req) {
  // Local single-user mode is open (mirrors GET /api/config). In supabase mode
  // require a session — current trust mode / model are operationally sensitive.
  if (getAuthMode() !== 'local') {
    try {
      await requireSession(req);
    } catch (err) {
      const status = err && typeof err === 'object' && err.status ? err.status : 401;
      return Response.json({ error: 'unauthorized' }, { status });
    }
  }

  let secretNames = new Set();
  try {
    secretNames = new Set(listSecrets().map((s) => s.name));
  } catch {
    // If the secrets table is unavailable, every secret simply reads as 'unset'.
  }

  const actions = SETTING_ACTIONS.map((action) => ({
    id: action.id,
    current: resolveCurrent(action, secretNames),
  }));

  return Response.json({ ok: true, actions, articles: HELP_ARTICLE_META });
}
