/**
 * ════════════════════════════════════════════════════════
 * bd sell bazar — sitemap-generator.js
 * server.js এ এই route যোগ করুন — Dynamic Product Sitemap
 * ════════════════════════════════════════════════════════
 *
 * server.js এ নিচের দুটি route যোগ করুন:
 * ১. GET /sitemap.xml       — Static sitemap serve করবে
 * ২. GET /sitemap-products.xml — Dynamic product sitemap
 *
 * ══ USAGE: server.js এ এই কোড পেস্ট করুন ══
 */

// ✅ Static sitemap.xml serve করুন (public folder থেকে)
app.get('/sitemap.xml', (req, res) => {
  const sitemapPath = path.join(__dirname, 'public', 'sitemap.xml');
  if (fs.existsSync(sitemapPath)) {
    res.set('Content-Type', 'application/xml; charset=utf-8');
    res.set('Cache-Control', 'public, max-age=3600'); // 1 ঘন্টা cache
    res.sendFile(sitemapPath);
  } else {
    // Fallback: inline static sitemap
    res.set('Content-Type', 'application/xml; charset=utf-8');
    res.send(generateStaticSitemap());
  }
});

// ✅ robots.txt serve করুন
app.get('/robots.txt', (req, res) => {
  const robotsPath = path.join(__dirname, 'public', 'robots.txt');
  if (fs.existsSync(robotsPath)) {
    res.set('Content-Type', 'text/plain; charset=utf-8');
    res.sendFile(robotsPath);
  } else {
    res.set('Content-Type', 'text/plain; charset=utf-8');
    res.send(generateRobotsTxt());
  }
});

// ✅ Dynamic Product Sitemap — প্রতিটি পণ্য আলাদা URL হিসেবে
app.get('/sitemap-products.xml', async (req, res) => {
  try {
    const products = await Product.find({ isActive: true })
      .select('name banglaName slug category categoryBangla updatedAt colors tags')
      .sort({ updatedAt: -1 })
      .lean();

    const baseUrl = 'https://bdsellbazar.shop';
    const today = new Date().toISOString().split('T')[0];

    let urls = '';
    products.forEach(p => {
      const slug = p.slug || encodeURIComponent(p.name.toLowerCase().replace(/\s+/g, '-'));
      const productUrl = `${baseUrl}/?product=${slug}`;
      const lastmod = p.updatedAt ? new Date(p.updatedAt).toISOString().split('T')[0] : today;
      const image = p.colors && p.colors[0] ? p.colors[0].image : '';
      const imgTitle = `${p.banglaName || p.name} – বিডি সেল বাজার`;
      const imgCaption = `${p.banglaName || p.name} | ${p.categoryBangla || p.category} | bd sell bazar`;

      urls += `
  <url>
    <loc>${productUrl}</loc>
    <lastmod>${lastmod}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.85</priority>
    <xhtml:link rel="alternate" hreflang="bn-BD" href="${productUrl}"/>
    <xhtml:link rel="alternate" hreflang="en"    href="${productUrl}"/>
    ${image ? `<image:image>
      <image:loc>${image}</image:loc>
      <image:title>${escapeXml(imgTitle)}</image:title>
      <image:caption>${escapeXml(imgCaption)}</image:caption>
    </image:image>` : ''}
  </url>`;
    });

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <!-- bd sell bazar — Product Sitemap — Auto-generated: ${today} -->
  <!-- মোট পণ্য: ${products.length}টি -->
${urls}
</urlset>`;

    res.set('Content-Type', 'application/xml; charset=utf-8');
    res.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
    res.send(xml);
  } catch (e) {
    console.error('[Sitemap] Error:', e.message);
    res.status(500).send('<?xml version="1.0"?><urlset></urlset>');
  }
});

// ✅ Sitemap Index — Google কে দুটো sitemap একসাথে জানাবে
app.get('/sitemap-index.xml', (req, res) => {
  const today = new Date().toISOString().split('T')[0];
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>https://bdsellbazar.shop/sitemap.xml</loc>
    <lastmod>${today}</lastmod>
  </sitemap>
  <sitemap>
    <loc>https://bdsellbazar.shop/sitemap-products.xml</loc>
    <lastmod>${today}</lastmod>
  </sitemap>
</sitemapindex>`;
  res.set('Content-Type', 'application/xml; charset=utf-8');
  res.send(xml);
});

// ✅ XML Escape helper
function escapeXml(str) {
  if (!str) return '';
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

function generateStaticSitemap() {
  return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>https://bdsellbazar.shop/</loc><priority>1.0</priority></url>
  <url><loc>https://bdsellbazar.shop/?category=attar</loc><priority>0.9</priority></url>
  <url><loc>https://bdsellbazar.shop/?category=soap</loc><priority>0.9</priority></url>
</urlset>`;
}

function generateRobotsTxt() {
  return `User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /admin/\nSitemap: https://bdsellbazar.shop/sitemap.xml\nSitemap: https://bdsellbazar.shop/sitemap-products.xml`;
}