import express from 'express';
import RSS from 'rss';
import { getMessagesByChannel, getAllChannels, getAllMessages } from './database.js';

const router = express.Router();

// Channel emoji badges (add more as needed)
const CHANNEL_EMOJIS = {
  'noticias': '📢',
  'eventos': '📅',
  'changelog': '🔄',
  'general': '💬',
  'announcements': '📣',
};

// Parse channel names from environment variable
function getChannelNames() {
  const namesStr = process.env.CHANNEL_NAMES || '';
  const names = {};
  if (namesStr) {
    namesStr.split(',').forEach(pair => {
      const [id, name] = pair.split('=');
      if (id && name) {
        names[id.trim()] = name.trim();
      }
    });
  }
  return names;
}

function getChannelDisplayName(channelId) {
  const names = getChannelNames();
  return names[channelId] || channelId;
}

function getChannelEmoji(channelName) {
  return CHANNEL_EMOJIS[channelName.toLowerCase()] || '📄';
}

function generateRSSFeed(messages, channelInfo, feedUrlSuffix = null) {
  const isCombined = channelInfo === 'All Channels';
  const feed = new RSS({
    title: `Discord - ${channelInfo}`,
    description: isCombined ? 'Latest messages from all channels' : `Messages from ${channelInfo}`,
    feed_url: `${process.env.BASE_URL || 'http://localhost:3000'}/rss/${feedUrlSuffix || channelInfo}`,
    site_url: process.env.BASE_URL || 'http://localhost:3000',
    language: 'en',
    pubDate: new Date(),
    ttl: 60,
  });

  for (const msg of messages) {
    const pubDate = new Date(msg.created_at);
    const channelName = getChannelDisplayName(msg.channel_id);
    const emoji = getChannelEmoji(channelName);

    // HTML-formatted description with visual badge
    const formattedDescription = `
      <div style="margin-bottom: 8px;">
        <span style="display: inline-block; background: #5865F2; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold;">
          ${emoji} ${channelName}
        </span>
      </div>
      <div style="border-left: 3px solid #5865F2; padding-left: 12px; margin-top: 8px;">
        ${msg.content}
      </div>
    `.trim();

    feed.item({
      title: `${emoji} [${channelName}] ${pubDate.toLocaleString()}`,
      description: formattedDescription,
      categories: [
        { name: channelName },
        { name: msg.author_name },
      ],
      url: `https://discord.com/channels/_/${msg.channel_id}/${msg.id}`,
      guid: msg.id,
      date: pubDate,
      author: msg.author_name,
    });
  }

  return feed.xml({ indent: true });
}

// GET /rss - List all available channels
router.get('/', (req, res) => {
  const channels = getAllChannels();
  res.json({
    channels: channels.map(c => ({
      channelId: c.channel_id,
      feedUrl: `/rss/${c.channel_id}`,
    })),
  });
});

// GET /rss/all - Combined RSS feed from all channels
router.get('/all', (req, res) => {
  const limit = parseInt(req.query.limit, 10) || 50;

  const messages = getAllMessages(limit);

  if (messages.length === 0) {
    return res.status(404).json({
      error: 'No messages found',
      hint: 'Make sure the bot has fetched messages from channels',
    });
  }

  const xml = generateRSSFeed(messages, 'All Channels', 'all');
  res.type('application/rss+xml').send(xml);
});

// GET /rss/:channelId - RSS feed for specific channel
router.get('/:channelId', (req, res) => {
  const { channelId } = req.params;
  const limit = parseInt(req.query.limit, 10) || 50;

  const messages = getMessagesByChannel(channelId, limit);

  if (messages.length === 0) {
    return res.status(404).json({
      error: 'No messages found for this channel',
      hint: 'Make sure the bot has fetched messages from this channel',
    });
  }

  const displayName = getChannelDisplayName(channelId);
  const xml = generateRSSFeed(messages, displayName, channelId);
  res.type('application/rss+xml').send(xml);
});

export default router;
