const express = require("express");
const rateLimit = require("express-rate-limit");
const router = express.Router();
const { ChatSession, ChatMessage } = require("../models");
const { generateAnswer, NO_INFO_MESSAGE } = require("../services/chatbotService");

// Équivalent ChatThrottle (AnonRateThrottle "20/min")
const chatLimiter = rateLimit({ windowMs: 60 * 1000, max: 20 });

// POST /api/v1/chatbot/message/
router.post("/message/", chatLimiter, async (req, res) => {
  const { session_id, message, language } = req.body || {};
  const lang = ["fr", "en"].includes(language) ? language : "fr";

  if (!session_id || !message) {
    return res.status(400).json({ detail: "session_id et message sont requis." });
  }

  try {
    const [session] = await ChatSession.findOrCreate({
      where: { session_id },
      defaults: { language: lang },
    });
    await ChatMessage.create({ session_id: session.id, role: "user", content: message });

    const { reply, source } = await generateAnswer(message, lang);

    await ChatMessage.create({
      session_id: session.id, role: "assistant", content: reply, answer_source: source,
    });

    res.json({ reply, session_id });
  } catch (err) {
    // Filet de sécurité ultime : jamais de 500 brut renvoyé au widget de chat.
    console.error("Erreur inattendue dans la route chatbot.", err);
    res.json({ reply: NO_INFO_MESSAGE[lang] || NO_INFO_MESSAGE.fr, session_id });
  }
});

module.exports = router;
