'use strict';

const express = require('express');
const rateLimit = require('express-rate-limit');

function buildBotRoutes(opts) {
  const { state, logger, rateLimits } = opts;
  const router = express.Router();

  const chatLimiter = rateLimit({
    windowMs: 60 * 1000,
    max: rateLimits?.broadcast_chat_per_min || 30,
    standardHeaders: true,
    legacyHeaders: false,
    handler: (req, res) => res.status(429).json({ error: 'Too many chat broadcasts. Slow down.' }),
  });

  router.post('/chat', chatLimiter, (req, res) => {
    const message = (req.body?.message || '').trim();
    if (!message) return res.status(400).json({ error: 'Message required.' });
    if (message.length > 256) return res.status(400).json({ error: 'Message too long (max 256 chars).' });
    let sent = 0;
    for (const b of state.activeBots.values()) {
      if (b.sendChat(message)) sent++;
    }
    logger.info(`[BROADCAST] "${message}" → ${sent} bots`);
    res.json({ success: true, sent });
  });

  router.post('/:id/remove', (req, res) => {
    const bot = state.activeBots.get(req.params.id);
    if (!bot) return res.status(404).json({ error: 'Not found' });
    bot.stop('manual-remove');
    res.json({ success: true });
  });

  router.post('/:id/kick', (req, res) => {
    const bot = state.activeBots.get(req.params.id);
    if (!bot) return res.status(404).json({ error: 'Not found' });
    const reason = req.body?.reason || 'kicked';
    bot.stop(reason);
    res.json({ success: true });
  });

  router.get('/:id', (req, res) => {
    const bot = state.activeBots.get(req.params.id);
    if (!bot) return res.status(404).json({ error: 'Not found' });
    res.json({ bot: bot.toJSON() });
  });

  router.post('/:id/chat', (req, res) => {
    const bot = state.activeBots.get(req.params.id);
    if (!bot) return res.status(404).json({ error: 'Not found' });
    const message = (req.body?.message || '').trim();
    if (!message) return res.status(400).json({ error: 'Message required.' });
    if (!bot.sendChat(message)) return res.status(409).json({ error: 'Bot not in a chat-eligible state.' });
    res.json({ success: true });
  });

  return router;
}

module.exports = { buildBotRoutes };
