const express = require('express'); const db = require('../db'); const { requireAuth } = require('../auth'); const { resolveActingProfile } = require('../lib/account'); const { loadCalendarDays } = require('../lib/queries'); const router = express.Router(); router.use(requireAuth); const BUSINESS_TYPES = ['small_business', 'company', 'authority']; async function acting(req) { const profileId = (req.body && req.body.profileId) || req.query.profileId; return resolveActingProfile(req.account, profileId); } // GET /api/calendar?profileId= router.get('/calendar', async (req, res) => { const { profile } = await acting(req); res.json({ days: await loadCalendarDays(profile ? profile.id : 0) }); }); // POST /api/events {profileId, date, time, title, location} router.post('/events', async (req, res) => { const { profile } = await acting(req); if (!profile) return res.status(400).json({ error: 'no_profile' }); if (!BUSINESS_TYPES.includes(profile.profile_type)) return res.status(403).json({ error: 'not_allowed' }); const date = String(req.body.date || '').trim().slice(0, 10); const time = String(req.body.time || '').trim().slice(0, 5); const title = String(req.body.title || '').trim().slice(0, 50); const location = String(req.body.location || '').trim().slice(0, 50); if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return res.status(400).json({ error: 'invalid_date' }); if (!/^\d{2}:\d{2}$/.test(time)) return res.status(400).json({ error: 'invalid_time' }); if (!title) return res.status(400).json({ error: 'title_required' }); await db.insert( 'INSERT INTO bleeter_events (author_profile_id, title, location, starts_at) VALUES (?, ?, ?, ?)', [profile.id, title, location || null, `${date} ${time}:00`] ); res.json({ ok: true }); }); // DELETE /api/events/:id {profileId} router.delete('/events/:id', async (req, res) => { const { profile } = await acting(req); if (!profile) return res.status(400).json({ error: 'no_profile' }); const eventId = Number(req.params.id); const ev = await db.q1('SELECT author_profile_id FROM bleeter_events WHERE id = ? AND deleted_at IS NULL', [eventId]); if (!ev) return res.status(404).json({ error: 'not_found' }); if (Number(ev.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' }); await db.exec("UPDATE bleeter_events SET deleted_at = NOW(), status = 'deleted' WHERE id = ?", [eventId]); res.json({ ok: true }); }); module.exports = router;