import { pool } from '../pool.js'; import { recordAudit } from './audit_stub.js'; export async function create({ slug, name, description, theme }, actor) { const { rows: [r] } = await pool.query( `INSERT INTO spaces(slug, name, description, theme) VALUES($1,$2,$3,$4) RETURNING *`, [slug, name, description || null, theme || null] ); await recordAudit(actor, 'create', 'space', r.id, null, r); return r; } export async function getById(id) { const { rows: [r] } = await pool.query( `SELECT * FROM spaces WHERE id=$1`, [id]); return r; } export async function getBySlug(slug) { const { rows: [r] } = await pool.query( `SELECT * FROM spaces WHERE slug=$1`, [slug]); return r; } export async function list() { const { rows } = await pool.query(`SELECT * FROM spaces ORDER BY name`); return rows; } export async function update(id, patch, actor) { const before = await getById(id); const fields = ['name','description','theme','slug']; const sets = [], vals = []; let i = 1; for (const f of fields) { if (patch[f] !== undefined) { sets.push(`${f}=$${i++}`); vals.push(patch[f]); } } sets.push(`updated_at=now()`); vals.push(id); const { rows: [r] } = await pool.query( `UPDATE spaces SET ${sets.join(', ')} WHERE id=$${i} RETURNING *`, vals ); await recordAudit(actor, 'update', 'space', id, before, r); return r; } export async function del(id, actor) { const before = await getById(id); await pool.query(`DELETE FROM spaces WHERE id=$1`, [id]); await recordAudit(actor, 'delete', 'space', id, before, null); }