/**
 * lib/help/articles.js — server-only loader for help article bodies.
 *
 * Metadata lives in lib/help/registry.js (client-safe). The markdown body for
 * each article lives in content/help/<slug>.md and is read here on the server so
 * the client search index stays small. Bodies are first-party markdown; they are
 * rendered with react-markdown WITHOUT raw-HTML support.
 */

import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { HELP_ARTICLE_META, getArticleMeta } from './registry.js';

const CONTENT_DIR = join(process.cwd(), 'content', 'help');

/** All articles, metadata only (no bodies). */
export function listArticles() {
  return HELP_ARTICLE_META;
}

/**
 * Load a single article (metadata + markdown body).
 * Returns null for an unknown slug. Throws only on unexpected fs errors.
 */
export function getArticle(slug) {
  // Defense-in-depth: only ever read files named by an allowlisted, safe slug.
  // getArticleMeta already gates on the registry, but assert the format too so
  // a future refactor can't turn this into a path-traversal read.
  if (typeof slug !== 'string' || !/^[a-z0-9-]+$/.test(slug)) return null;
  const meta = getArticleMeta(slug);
  if (!meta) return null;
  let body;
  try {
    body = readFileSync(join(CONTENT_DIR, `${slug}.md`), 'utf8');
  } catch (err) {
    if (err && err.code === 'ENOENT') return null;
    throw err;
  }
  return { ...meta, body };
}
