const express = require('express'); const router = express.Router(); const { query } = require('../config/db'); const channelsSvc = require('../services/channels'); const generationQueue = require('../workers/generation'); // POST /api/generate — создать задачу генерации router.post('/', async (req, res) => { try { const { type, topic, channelId, rubric, keywords = [], useCritique = true } = req.body; const userId = req.headers['x-user-id'] || null; if (!type) return res.status(400).json({ error: 'type is required' }); if (!['post', 'article', 'topics'].includes(type)) return res.status(400).json({ error: 'Invalid type' }); if (type !== 'topics' && !topic) return res.status(400).json({ error: 'topic is required' }); if (type === 'post' && !channelId) return res.status(400).json({ error: 'channelId is required for posts' }); const { rows } = await query( `INSERT INTO generation_jobs (user_id, channel_id, type, topic, rubric, status) VALUES ($1,$2,$3,$4,$5,'pending') RETURNING id`, [userId, channelId || null, type, topic || null, rubric || null] ); const jobId = rows[0].id; await generationQueue.add({ jobId, type, topic, channelId, rubric, keywords, useCritique }); res.json({ jobId, status: 'pending' }); } catch (err) { console.error('[Route] POST /generate', err); res.status(500).json({ error: err.message }); } }); // GET /api/generate/:id — статус и результат router.get('/:id', async (req, res) => { try { const { rows } = await query(`SELECT * FROM generation_jobs WHERE id=$1`, [req.params.id]); if (!rows.length) return res.status(404).json({ error: 'Job not found' }); res.json(rows[0]); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;