import { Router } from 'express'; import { z } from 'zod'; import * as repo from '../../db/repos/spaces.js'; import { validate } from '../validate.js'; import { NotFoundError, asyncWrap } from '../errors.js'; const createSchema = z.object({ slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/), name: z.string().min(1).max(200), description: z.string().optional(), theme: z.string().optional() }); const patchSchema = z.object({ slug: z.string().min(1).max(64).regex(/^[a-z0-9-]+$/).optional(), name: z.string().min(1).max(200).optional(), description: z.string().nullable().optional(), theme: z.string().nullable().optional() }); const uuidParams = z.object({ id: z.string().uuid() }); export const router = Router(); router.get('/', asyncWrap(async (_req, res) => { res.json(await repo.list()); })); router.post('/', validate({ body: createSchema }), asyncWrap(async (req, res) => { const row = await repo.create(req.body, req.actor); res.status(201).json(row); }) ); router.get('/by-slug/:slug', asyncWrap(async (req, res) => { const row = await repo.getBySlug(req.params.slug); if (!row) throw new NotFoundError('space not found'); res.json(row); })); router.get('/:id', validate({ params: uuidParams }), asyncWrap(async (req, res) => { const row = await repo.getById(req.params.id); if (!row) throw new NotFoundError('space not found'); res.json(row); }) ); router.patch('/:id', validate({ params: uuidParams, body: patchSchema }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('space not found'); const row = await repo.update(req.params.id, req.body, req.actor); res.json(row); }) ); router.delete('/:id', validate({ params: uuidParams }), asyncWrap(async (req, res) => { const existing = await repo.getById(req.params.id); if (!existing) throw new NotFoundError('space not found'); await repo.del(req.params.id, req.actor); res.status(204).end(); }) );