const router = require('express').Router(); const { query } = require('../db'); const { runEnrichTick, enrichWordsSync } = require('../lib/enrichWords'); const STATUSES = ['requested', 'translated', 'generated', 'blocked', 'published']; const STATUS_TIMESTAMP = { requested: 'requested_at', published: 'published_at', blocked: 'blocked_at', }; // POST /api/words/enrich-batch — manueller Trigger für Wort-Anreicherung router.post('/enrich-batch', async (req, res, next) => { try { const sync = req.query.sync === 'true'; if (sync) { const max = parseInt(req.query.max) || 500; return res.json(await enrichWordsSync({ max })); } res.json(await runEnrichTick()); } catch (err) { next(err); } }); // GET /api/words router.get('/', async (req, res, next) => { try { const { status, titel_de, search, dom_pos, level, themenfeld_id, has_conc_m, limit = 50, offset = 0 } = req.query; const params = [Math.min(parseInt(limit), 500), parseInt(offset)]; const conditions = []; if (status) { conditions.push(`w.status = $${params.length + 1}`); params.push(status); } if (titel_de) { conditions.push(`lower(w.titel_de) = lower($${params.length + 1})`); params.push(titel_de); } if (dom_pos) { conditions.push(`w.dom_pos = $${params.length + 1}`); params.push(dom_pos); } if (level) { conditions.push(`w.level = $${params.length + 1}`); params.push(level); } if (themenfeld_id) { conditions.push(`w.themenfeld_id = $${params.length + 1}`); params.push(themenfeld_id); } if (has_conc_m === 'true') conditions.push(`w.conc_m IS NOT NULL`); if (has_conc_m === 'false') conditions.push(`w.conc_m IS NULL`); if (search) { const p = `%${search.toLowerCase()}%`; conditions.push(`(lower(w.titel_de) LIKE $${params.length + 1} OR lower(w.titel_en) LIKE $${params.length + 1} OR lower(w.titel_sv) LIKE $${params.length + 1})`); params.push(p); } const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; const result = await query( `SELECT w.*, COALESCE(json_agg(DISTINCT p.id) FILTER (WHERE p.id IS NOT NULL), '[]') AS picture_ids, COALESCE(json_agg(DISTINCT c.id) FILTER (WHERE c.id IS NOT NULL), '[]') AS category_ids, COUNT(DISTINCT wp2.picture_id)::int AS picture_count FROM words w LEFT JOIN word_pictures wp ON wp.word_id = w.id LEFT JOIN pictures p ON p.id = wp.picture_id LEFT JOIN word_categories wc ON wc.word_id = w.id LEFT JOIN categories c ON c.id = wc.category_id LEFT JOIN word_pictures wp2 ON wp2.word_id = w.id ${where} GROUP BY w.id ORDER BY w.created_at DESC LIMIT $1 OFFSET $2`, params ); res.json(result.rows); } catch (err) { next(err); } }); // Hilfsfunktion: wenn alle 3 Sprachen gefüllt sind und Status `requested`, auto → `translated`. function autoTranslatedStatus(row) { return (row.titel_de && row.titel_en && row.titel_sv && row.status === 'requested') ? 'translated' : null; } // POST /api/words router.post('/', async (req, res, next) => { try { const { titel_de, titel_en, titel_sv, difficulty_level, status, conc_m } = req.body; if (status && !STATUSES.includes(status)) return res.status(400).json({ error: `status must be one of: ${STATUSES.join(', ')}` }); // Auto: alle 3 Sprachen direkt mitgeliefert + kein expliziter Status → 'translated' const allLangs = titel_de && titel_en && titel_sv; const effectiveStatus = status || (allLangs ? 'translated' : 'requested'); // Upsert: neu anlegen oder bei doppeltem titel_en nur conc_m aktualisieren let result = await query( `INSERT INTO words (titel_de, titel_en, titel_sv, difficulty_level, status, conc_m, requested_at) VALUES ($1, $2, $3, $4, $5, $6, NOW()) RETURNING *, true AS is_insert`, [titel_de || null, titel_en || null, titel_sv || null, difficulty_level || null, effectiveStatus, conc_m ?? null] ).catch(async err => { if (err.code === '23505' && titel_en) { // Duplikat auf titel_en → conc_m aktualisieren und bestehende Zeile zurückgeben const upd = await query( `UPDATE words SET conc_m = $1 WHERE titel_en = $2 RETURNING *, false AS is_insert`, [conc_m ?? null, titel_en] ); return upd; } throw err; }); const row = result.rows[0]; const { is_insert, ...word } = row; res.status(is_insert ? 201 : 200).json({ ...word, picture_ids: [], category_ids: [] }); } catch (err) { next(err); } }); // PATCH /api/words/:id router.patch('/:id', async (req, res, next) => { try { const allowed = ['titel_de', 'titel_en', 'titel_sv', 'status', 'difficulty_level', 'requested_at', 'published_at', 'blocked_at', 'conc_m', 'dom_pos', 'level', 'themenfeld_id']; const fields = Object.keys(req.body).filter(k => allowed.includes(k)); if (!fields.length) return res.status(400).json({ error: 'No valid fields provided' }); if (req.body.status && !STATUSES.includes(req.body.status)) return res.status(400).json({ error: `status must be one of: ${STATUSES.join(', ')}` }); // Auto-timestamp bei Statuswechsel const tsField = STATUS_TIMESTAMP[req.body.status]; if (tsField && !req.body[tsField]) { fields.push(tsField); req.body[tsField] = new Date().toISOString(); } const setClauses = fields.map((f, i) => `${f} = $${i + 1}`).join(', '); const values = [...fields.map(f => req.body[f]), req.params.id]; const result = await query( `UPDATE words SET ${setClauses} WHERE id = $${fields.length + 1} RETURNING *`, values ); if (!result.rows.length) return res.status(404).json({ error: 'Not found' }); // Auto-Übergang: requested → translated wenn jetzt alle 3 Sprachen gefüllt sind let row = result.rows[0]; const next = autoTranslatedStatus(row); if (next) { const upd = await query(`UPDATE words SET status = $1 WHERE id = $2 RETURNING *`, [next, row.id]); row = upd.rows[0]; } res.json(row); } catch (err) { next(err); } }); // DELETE /api/words/:id router.delete('/:id', async (req, res, next) => { try { const result = await query('DELETE FROM words WHERE id = $1 RETURNING id', [req.params.id]); if (!result.rows.length) return res.status(404).json({ error: 'Not found' }); res.status(204).end(); } catch (err) { next(err); } }); // GET /api/words/:id — AFTER sub-routes to avoid shadowing router.get('/:id', async (req, res, next) => { try { const result = await query( `SELECT w.*, COALESCE(json_agg(DISTINCT p.id) FILTER (WHERE p.id IS NOT NULL), '[]') AS picture_ids, COALESCE(json_agg(DISTINCT c.id) FILTER (WHERE c.id IS NOT NULL), '[]') AS category_ids, COUNT(DISTINCT wp2.picture_id)::int AS picture_count FROM words w LEFT JOIN word_pictures wp ON wp.word_id = w.id LEFT JOIN pictures p ON p.id = wp.picture_id LEFT JOIN word_categories wc ON wc.word_id = w.id LEFT JOIN categories c ON c.id = wc.category_id LEFT JOIN word_pictures wp2 ON wp2.word_id = w.id WHERE w.id = $1 GROUP BY w.id`, [req.params.id] ); if (!result.rows.length) return res.status(404).json({ error: 'Not found' }); res.json(result.rows[0]); } catch (err) { next(err); } }); // GET /api/words/:id/pictures — verknüpfte Bilder laden router.get('/:id/pictures', async (req, res, next) => { try { const result = await query( `SELECT p.* FROM pictures p JOIN word_pictures wp ON wp.picture_id = p.id WHERE wp.word_id = $1 ORDER BY p.created_at DESC`, [req.params.id] ); res.json(result.rows); } catch (err) { next(err); } }); // GET /api/words/:id/categories — verknüpfte Kategorien laden router.get('/:id/categories', async (req, res, next) => { try { const result = await query( `SELECT c.* FROM categories c JOIN word_categories wc ON wc.category_id = c.id WHERE wc.word_id = $1 ORDER BY c.name_de`, [req.params.id] ); res.json(result.rows); } catch (err) { next(err); } }); // POST /api/words/:id/pictures/:pictureId — Bild verknüpfen router.post('/:id/pictures/:pictureId', async (req, res, next) => { try { await query( `INSERT INTO word_pictures (word_id, picture_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [req.params.id, req.params.pictureId] ); res.status(204).end(); } catch (err) { next(err); } }); // DELETE /api/words/:id/pictures/:pictureId — Bild-Verknüpfung entfernen router.delete('/:id/pictures/:pictureId', async (req, res, next) => { try { await query( `DELETE FROM word_pictures WHERE word_id = $1 AND picture_id = $2`, [req.params.id, req.params.pictureId] ); res.status(204).end(); } catch (err) { next(err); } }); // POST /api/words/:id/categories/:categoryId — Kategorie verknüpfen router.post('/:id/categories/:categoryId', async (req, res, next) => { try { await query( `INSERT INTO word_categories (word_id, category_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [req.params.id, req.params.categoryId] ); res.status(204).end(); } catch (err) { next(err); } }); // DELETE /api/words/:id/categories/:categoryId — Kategorie-Verknüpfung entfernen router.delete('/:id/categories/:categoryId', async (req, res, next) => { try { await query( `DELETE FROM word_categories WHERE word_id = $1 AND category_id = $2`, [req.params.id, req.params.categoryId] ); res.status(204).end(); } catch (err) { next(err); } }); module.exports = router;