import express from 'express'; import { GoogleGenerativeAI } from '@google/generative-ai'; import jwt from 'jsonwebtoken'; const router = express.Router(); const JWT_SECRET = process.env.JWT_SECRET || 'secret'; const API_KEY = process.env.API_KEY; const MODEL_ID = 'gemini-1.5-flash'; const authenticate = (req: any, res: any, next: any) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).json({ error: 'Unauthorized' }); try { const decoded = jwt.verify(token, JWT_SECRET) as any; req.user = decoded; next(); } catch { res.status(401).json({ error: 'Invalid token' }); } }; router.use(authenticate); router.post('/chat', async (req, res) => { try { const { history, message } = req.body; if (!API_KEY) { return res.status(500).json({ error: 'AI service not configured' }); } const ai = new GoogleGenerativeAI(API_KEY); const { systemInstruction, userMessage } = req.body; const model = ai.getGenerativeModel({ model: MODEL_ID, systemInstruction }); const result = await model.generateContent(userMessage); const response = result.response.text(); res.json({ response }); } catch (error) { console.error(error); res.status(500).json({ error: String(error) }); } }); export default router;