const { SitemapStream, streamToPromise } = require('sitemap');
const { Readable } = require('stream');

// Handle sitemap.xml route
app.get('/sitemap.xml', async (req, res) => {
  try {
    const links = [
      { url: '/', changefreq: 'daily', priority: 1.0 },
      { url: '/about', changefreq: 'monthly', priority: 0.8 },
      { url: '/services', changefreq: 'monthly', priority: 0.8 },
      { url: '/contact', changefreq: 'monthly', priority: 0.8 },
      { url: '/book', changefreq: 'weekly', priority: 0.9 },
      { url: '/internship', changefreq: 'weekly', priority: 0.9 },
      { url: '/dashboard', changefreq: 'daily', priority: 1.0 },
    ];

    // Dynamically add URLs based on data (like submitted bookings or blog posts, if any)
    const bookingLinks = await Booking.find().lean(); // Or other data source
    bookingLinks.forEach(booking => {
      links.push({ url: `/booking/${booking._id}`, changefreq: 'weekly', priority: 0.6 });
    });

    const stream = new SitemapStream({ hostname: `http://localhost:${port}` });
    res.writeHead(200, {
      'Content-Type': 'application/xml'
    });

    const xmlData = await streamToPromise(Readable.from(links).pipe(stream)).then((data) => data.toString());
    res.end(xmlData);
  } catch (error) {
    console.error('Error generating sitemap:', error);
    res.status(500).send('Error generating sitemap');
  }
});
