import express from 'express';
import api from '../config/api.js';

const router = express.Router();

const STATIC_PATHS = [
  '/', '/tours', '/destinations', '/blog', '/about', '/contact', '/faq',
  '/privacy-policy', '/terms-conditions', '/cancellation-policy', '/login', '/register'
];

router.get('/robots.txt', (req, res) => {
  const siteUrl = `${req.protocol}://${req.get('host')}`;
  res.type('text/plain').send(
    `User-agent: *\nAllow: /\n\nSitemap: ${siteUrl}/sitemap.xml\n`
  );
});

router.get('/sitemap.xml', async (req, res) => {
  const siteUrl = `${req.protocol}://${req.get('host')}`;
  try {
    const { data } = await api.get('/public/sitemap-data');

    const urls = [
      ...STATIC_PATHS.map((p) => ({ loc: `${siteUrl}${p}`, priority: p === '/' ? '1.0' : '0.7' })),
      ...data.tours.map((id) => ({ loc: `${siteUrl}/tours/${id}`, priority: '0.8' })),
      ...data.destinations.map((slug) => ({ loc: `${siteUrl}/destinations/${slug}`, priority: '0.6' })),
      ...data.blogs.map((b) => ({
        loc: `${siteUrl}/blog/${b.slug}`,
        priority: '0.6',
        lastmod: b.updatedAt ? new Date(b.updatedAt).toISOString().split('T')[0] : undefined
      }))
    ];

    const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls
      .map(
        (u) =>
          `  <url><loc>${u.loc}</loc>${u.lastmod ? `<lastmod>${u.lastmod}</lastmod>` : ''}<priority>${u.priority}</priority></url>`
      )
      .join('\n')}\n</urlset>`;

    res.type('application/xml').send(xml);
  } catch (err) {
    console.error('Sitemap generation error:', err.message);
    res.status(500).type('text/plain').send('Failed to generate sitemap.');
  }
});

export default router;
