import { requireAdmin } from '../../../utils/auth' import { writeAuditLog } from '../../../utils/audit' import { useDatabase } from '../../../utils/db' export default defineEventHandler(async (event) => { const user = await requireAdmin(event) const db = useDatabase() const timestamp = new Date().toISOString() const publish = db.transaction(() => { const row = db.prepare('SELECT draft_json FROM site_documents WHERE document_key = ?').get('website') as { draft_json: string } const versionRow = db.prepare(` SELECT COALESCE(MAX(version), 0) + 1 AS version FROM revisions WHERE entity_type = ? AND entity_key = ? `).get('site_document', 'website') as { version: number } db.prepare(` INSERT INTO revisions (entity_type, entity_key, version, snapshot_json, operator_id, action, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) `).run('site_document', 'website', versionRow.version, row.draft_json, user.id, 'publish', timestamp) db.prepare(` UPDATE site_documents SET published_json = draft_json, updated_by = ?, updated_at = ?, published_at = ? WHERE document_key = ? `).run(user.id, timestamp, timestamp, 'website') db.prepare(` DELETE FROM revisions WHERE entity_type = ? AND entity_key = ? AND id NOT IN ( SELECT id FROM revisions WHERE entity_type = ? AND entity_key = ? ORDER BY version DESC LIMIT 20 ) `).run('site_document', 'website', 'site_document', 'website') return versionRow.version }) const version = publish() writeAuditLog(event, { operatorId: user.id, action: 'publish', entityType: 'site_document', entityKey: 'website', metadata: { version } }) return { success: true, publishedAt: timestamp, version } })