import fs from 'node:fs/promises'; import path from 'node:path'; import { getDb } from '../db/index'; const DATA_DIR = process.env.DATA_DIR || path.join(process.cwd(), 'app', 'data'); export async function generateDraftConfig(): Promise { const db = getDb(); // 1. Globale Settings laden const settingsRow = db.prepare('SELECT value_json FROM site_settings WHERE key = ?').get('site_config') as { value_json: string } | undefined; const baseConfig = settingsRow ? JSON.parse(settingsRow.value_json) : {}; // 2. Alle Seiten laden const pagesRows = db.prepare('SELECT * FROM pages ORDER BY created_at ASC').all() as any[]; const pages = pagesRows.map((page) => { const sectionsRows = db.prepare('SELECT * FROM page_sections WHERE page_id = ? ORDER BY order_index ASC').all(page.id) as any[]; const sections = sectionsRows.map((sec) => { const draftContent = JSON.parse(sec.content_draft_json || '{}'); const styles = JSON.parse(sec.styles_json || '{}'); return { id: sec.id, type: sec.section_type, settings: { ...draftContent, ...styles } }; }); return { id: page.id, slug: page.slug, title: page.title, is_published: page.status === 'published', sections }; }); const fullDraftConfig = { ...baseConfig, pages, updated_at: new Date().toISOString() }; const draftPath = path.join(DATA_DIR, 'site.config.draft.json'); await fs.mkdir(DATA_DIR, { recursive: true }); await fs.writeFile(draftPath, JSON.stringify(fullDraftConfig, null, 2), 'utf-8'); return fullDraftConfig; } export async function publishLiveConfig(): Promise { const db = getDb(); // 1. In DB: Setze content_published_json = content_draft_json für alle Sektionen db.exec('UPDATE page_sections SET content_published_json = content_draft_json'); // 2. Globale Settings laden const settingsRow = db.prepare('SELECT value_json FROM site_settings WHERE key = ?').get('site_config') as { value_json: string } | undefined; const baseConfig = settingsRow ? JSON.parse(settingsRow.value_json) : {}; // 3. Alle veröffentlichten Seiten laden const pagesRows = db.prepare('SELECT * FROM pages WHERE status = ? ORDER BY created_at ASC').all('published') as any[]; const pages = pagesRows.map((page) => { const sectionsRows = db.prepare('SELECT * FROM page_sections WHERE page_id = ? ORDER BY order_index ASC').all(page.id) as any[]; const sections = sectionsRows.map((sec) => { const pubContent = JSON.parse(sec.content_published_json || '{}'); const styles = JSON.parse(sec.styles_json || '{}'); return { id: sec.id, type: sec.section_type, settings: { ...pubContent, ...styles } }; }); return { id: page.id, slug: page.slug, title: page.title, is_published: true, sections }; }); const fullLiveConfig = { ...baseConfig, pages, updated_at: new Date().toISOString() }; const livePath = path.join(DATA_DIR, 'site.config.json'); await fs.mkdir(DATA_DIR, { recursive: true }); await fs.writeFile(livePath, JSON.stringify(fullLiveConfig, null, 2), 'utf-8'); return fullLiveConfig; }