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

const router = express.Router();

function generateRSSFeed(messages, channelInfo) {
  const feed = new RSS({
    title: `Discord Channel - ${channelInfo}`,
    description: 'Messages from Discord channel',
    feed_url: `${process.env.BASE_URL || 'http://localhost:3000'}/rss/${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);
    feed.item({
      title: `Update patch from ${pubDate.toISOString()}`,
      description: msg.content,
      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/: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 xml = generateRSSFeed(messages, channelId);
  res.type('application/rss+xml').send(xml);
});

export default router;
