const express = require('express'); const db = require('../db'); const { requireAuth } = require('../auth'); const { resolveActingProfile } = require('../lib/account'); const { loadMarketplace } = require('../lib/queries'); const { isAllowedExternalUrl } = require('../lib/media'); const router = express.Router(); router.use(requireAuth); async function acting(req) { const profileId = (req.body && req.body.profileId) || req.query.profileId; return resolveActingProfile(req.account, profileId); } // GET /api/marketplace?profileId= router.get('/marketplace', async (req, res) => { const { profile } = await acting(req); res.json({ items: await loadMarketplace(profile ? profile.id : 0) }); }); // POST /api/marketplace {profileId, title, description, priceLabel, mediaUrl} router.post('/marketplace', async (req, res) => { const { profile } = await acting(req); if (!profile) return res.status(400).json({ error: 'no_profile' }); let title = String(req.body.title || '').trim().slice(0, 120); let description = String(req.body.description || '').trim().slice(0, 2000); const priceLabel = String(req.body.priceLabel || '').trim().slice(0, 80); const mediaUrl = String(req.body.mediaUrl || '').trim().slice(0, 500); if (!title && !description) return res.status(400).json({ error: 'empty' }); if (!description) description = title; if (!title) title = description.slice(0, 120); let mediaId = null; if (mediaUrl) { const check = isAllowedExternalUrl(mediaUrl); if (!check.ok) return res.status(400).json({ error: 'media_rejected', reason: check.reason }); mediaId = await db.insert('INSERT INTO bleeter_media (owner_profile_id, source_type, url) VALUES (?, ?, ?)', [profile.id, 'external_url', mediaUrl]); } await db.insert( `INSERT INTO bleeter_marketplace (author_profile_id, category, title, description, price_label, media_id) VALUES (?, 'general', ?, ?, ?, ?)`, [profile.id, title, description, priceLabel, mediaId] ); res.json({ ok: true }); }); // DELETE /api/marketplace/:id {profileId} router.delete('/marketplace/:id', async (req, res) => { const { profile } = await acting(req); if (!profile) return res.status(400).json({ error: 'no_profile' }); const entryId = Number(req.params.id); const entry = await db.q1('SELECT author_profile_id FROM bleeter_marketplace WHERE id = ? AND deleted_at IS NULL', [entryId]); if (!entry) return res.status(404).json({ error: 'not_found' }); if (Number(entry.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' }); await db.exec("UPDATE bleeter_marketplace SET deleted_at = NOW(), status = 'deleted' WHERE id = ?", [entryId]); res.json({ ok: true }); }); module.exports = router;