import db from "../sql.mjs"; export default (router, tpl) => { // Get unread notifications router.get('/api/notifications', async (req, res) => { if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) }); try { const notifications = await db` SELECT n.id, n.type, n.item_id, n.reference_id, n.created_at, n.is_read, u.user as from_user, u.id as from_user_id FROM notifications n JOIN comments c ON n.reference_id = c.id JOIN "user" u ON c.user_id = u.id WHERE n.user_id = ${req.session.id} AND n.is_read = false ORDER BY n.created_at DESC LIMIT 20 `; return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, notifications }) }); } catch (err) { console.error(err); return res.reply({ code: 500, body: JSON.stringify({ success: false }) }); } }); // Mark all as read router.post('/api/notifications/read', async (req, res) => { if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) }); try { await db`UPDATE notifications SET is_read = true WHERE user_id = ${req.session.id}`; return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) }); } catch (err) { return res.reply({ code: 500, body: JSON.stringify({ success: false }) }); } }); // Mark single as read (optional, for clicking) router.post(/\/api\/notifications\/(?\d+)\/read/, async (req, res) => { if (!req.session) return res.reply({ code: 401, body: JSON.stringify({ success: false }) }); const id = req.params.id; try { await db`UPDATE notifications SET is_read = true WHERE id = ${id} AND user_id = ${req.session.id}`; return res.reply({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true }) }); } catch (err) { return res.reply({ code: 500, body: JSON.stringify({ success: false }) }); } }); return router; };