// src/routes/chat.js
const express = require('express');
const crypto = require('crypto');
const db = require('../db');
const rateLimit = require('../middleware/rateLimit');
const { getChatReply } = require('../llm/provider');

const router = express.Router();

// PUBLIC — send a chat message, get a reply
router.post('/', rateLimit({ windowMs: 60_000, max: 15 }), async (req, res) => {
  const { messages, sessionId } = req.body || {};
  if (!Array.isArray(messages) || messages.length === 0) {
    return res.status(400).json({ error: 'messages array is required.' });
  }
  // keep only the last 10 turns and only role/content to avoid abuse via huge payloads
  const trimmed = messages.slice(-10).map((m) => ({
    role: m.role === 'assistant' ? 'assistant' : 'user',
    content: String(m.content || '').slice(0, 1000)
  }));

  const sid = sessionId && typeof sessionId === 'string' ? sessionId.slice(0, 64) : crypto.randomUUID();

  try {
    const reply = await getChatReply(trimmed);

    const lastUser = trimmed[trimmed.length - 1];
    const logStmt = db.prepare('INSERT INTO chat_logs (session_id, role, content) VALUES (?, ?, ?)');
    if (lastUser) logStmt.run(sid, 'user', lastUser.content);
    logStmt.run(sid, 'assistant', reply);

    res.json({ reply, sessionId: sid });
  } catch (err) {
    console.error('[chat] error:', err);
    res.status(500).json({ error: "Sorry, the chat assistant isn't available right now." });
  }
});

module.exports = router;
