import { getDatabase } from '../index.js'; /** Public wiki pages (M17). */ const parse = (row) => row ? { ...row, published: Boolean(row.published), protected: Boolean(row.protected) } : null; export function createPage({ slug, title, summary = null, content = '', category = 'Général', position = 0, published = false, isProtected = false, createdBy = null, }) { const { lastInsertRowid } = getDatabase() .prepare( `INSERT INTO wiki_pages (slug, title, summary, content, category, position, published, protected, created_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( slug, title, summary, content, category, position, published ? 1 : 0, isProtected ? 1 : 0, createdBy, createdBy, ); return getPage(Number(lastInsertRowid)); } export function getPage(id) { return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE id = ?').get(id) ?? null); } export function getPageBySlug(slug) { return parse(getDatabase().prepare('SELECT * FROM wiki_pages WHERE slug = ?').get(slug) ?? null); } /** Published pages only, in reading order — what the public site shows. */ export function listPublished() { return getDatabase() .prepare('SELECT * FROM wiki_pages WHERE published = 1 ORDER BY category, position, title') .all() .map(parse); } export function listAllPages() { return getDatabase() .prepare('SELECT * FROM wiki_pages ORDER BY category, position, title') .all() .map(parse); } const UPDATABLE = Object.freeze({ slug: (value) => value, title: (value) => value, summary: (value) => value, content: (value) => value, category: (value) => value, position: (value) => Number.parseInt(value, 10) || 0, published: (value) => (value ? 1 : 0), }); export function updatePage(id, patch, updatedBy = null) { const entries = Object.entries(patch).filter(([key]) => key in UPDATABLE); if (entries.length === 0) return getPage(id); const assignments = entries.map(([key]) => `${key} = ?`).join(', '); const values = entries.map(([key, value]) => UPDATABLE[key](value)); getDatabase() .prepare( `UPDATE wiki_pages SET ${assignments}, updated_by = ?, updated_at = datetime('now') WHERE id = ?`, ) .run(...values, updatedBy, id); return getPage(id); } export function removePage(id) { return getDatabase().prepare('DELETE FROM wiki_pages WHERE id = ? AND protected = 0').run(id).changes; } export function countPages() { return getDatabase().prepare('SELECT COUNT(*) AS count FROM wiki_pages').get().count; } /** Full-text-ish search over the published pages, good enough for a small wiki. */ export function searchPublished(term) { const needle = `%${term}%`; return getDatabase() .prepare( `SELECT * FROM wiki_pages WHERE published = 1 AND (title LIKE ? OR summary LIKE ? OR content LIKE ?) ORDER BY category, position, title LIMIT 25`, ) .all(needle, needle, needle) .map(parse); }