'use strict';

const express = require('express');
const router = express.Router();
const db = require('../db');

const BASE_URL = process.env.BASE_URL || 'http://localhost:3000';

/**
 * Escape a string for safe injection into XML text content.
 */
function escXml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

/**
 * GET /sitemap.xml
 *
 * Dynamically generated from the products table — always in sync
 * with the DB, no manual editing required when products are added,
 * removed, or renamed.
 *
 * Lists OUR OWN canonical SEO pages (/products/:slug), never the
 * external product_url values — a sitemap must only contain URLs
 * on our own domain.
 */
router.get('/sitemap.xml', async (req, res) => {
  try {
    const [rows] = await db.execute(
      `SELECT slug, updated_at FROM products ORDER BY id ASC`
    );

    const urlEntries = rows.map((product) => {
      const loc = `${BASE_URL}/products/${escXml(product.slug)}`;
      const lastmod = product.updated_at
        ? new Date(product.updated_at).toISOString().split('T')[0]
        : undefined;

      return `  <url>
    <loc>${loc}</loc>${lastmod ? `\n    <lastmod>${lastmod}</lastmod>` : ''}
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>`;
    }).join('\n');

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

  <!-- Homepage -->
  <url>
    <loc>${BASE_URL}/</loc>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>

  <!-- Product SEO pages — our own canonical URLs, generated from the DB -->
${urlEntries}

</urlset>
`;

    res.setHeader('Content-Type', 'application/xml; charset=utf-8');
    res.setHeader('Cache-Control', 'public, max-age=3600, must-revalidate');
    res.send(xml);

  } catch (err) {
    console.error('GET /sitemap.xml error:', err.message);
    res.status(500).send('Server error');
  }
});

module.exports = router;