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 }); } }); // POST /api/generate/transform — синхронная трансформация поста (короче/длиннее/улучшить) router.post('/transform', async (req, res) => { try { const { channelId, originalPost, action } = req.body; const userId = parseInt(req.headers['x-user-id']) || null; if (!channelId || !originalPost || !action) { return res.status(400).json({ error: 'channelId, originalPost, action required' }); } const channel = await channelsSvc.getChannel(userId, channelId); if (!channel) return res.status(404).json({ error: 'Channel not found' }); const ai = require('../services/ai'); const result = await ai.transformPost(channel, { originalPost, action }); res.json(result); } catch (err) { console.error('[Route] POST /transform', err); res.status(500).json({ error: err.message }); } }); // POST /api/generate/post-image — синхронная генерация картинки к посту router.post('/post-image', async (req, res) => { try { const { channelId, post } = req.body; const userId = parseInt(req.headers['x-user-id']) || null; if (!channelId || !post) return res.status(400).json({ error: 'channelId and post required' }); const channel = await channelsSvc.getChannel(userId, channelId); if (!channel) return res.status(404).json({ error: 'Channel not found' }); const { generatePostImage } = require('../services/postImages'); const result = await generatePostImage({ post, channel, style: channel.style || {} }); res.json(result); } catch (err) { console.error('[Route] POST /post-image', err); res.status(500).json({ error: err.message }); } }); // GET /api/generate/image-styles — список доступных стилей картинок router.get('/image-styles', async (_, res) => { const { IMAGE_STYLES, IMAGE_PALETTES } = require('../services/postImages'); res.json({ styles: Object.entries(IMAGE_STYLES).map(([v, s]) => ({ value: v, label: s.label })), palettes: Object.keys(IMAGE_PALETTES).map(v => ({ value: v, label: { auto: 'Авто', dark: 'Тёмная', light: 'Светлая', warm: 'Тёплая', cool: 'Холодная', mono: 'Монохром', vibrant: 'Яркая' }[v] || v })), }); }); // POST /api/generate/topics-ideas — синхронные идеи тем для канала router.post('/topics-ideas', async (req, res) => { try { const { channelId, count = 7 } = req.body; const userId = parseInt(req.headers['x-user-id']) || null; if (!channelId) return res.status(400).json({ error: 'channelId required' }); const channel = await channelsSvc.getChannel(userId, channelId); if (!channel) return res.status(404).json({ error: 'Channel not found' }); const ai = require('../services/ai'); const result = await ai.generateTopics(channel, count); res.json(result); } catch (err) { console.error('[Route] POST /topics-ideas', err); res.status(500).json({ error: err.message }); } }); module.exports = router;