// api/sitemap.js
const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SECRET_KEY
);

module.exports = async function handler(req, res) {
  let urls = '';

  try {
    const { data } = await supabase
      .from('shared_stories')
      .select('id, created_at')
      .order('created_at', { ascending: false })
      .limit(1000);

    urls = (data || []).map(s => `
  <url>
    <loc>https://wiki-tale.app/story/${s.id}</loc>
    <lastmod>${new Date(s.created_at).toISOString()}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>`).join('');
  } catch (e) {
    console.error('sitemap fetch error:', e.message);
    // Fail gracefully — still serve a valid sitemap with just the homepage.
  }

  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">
  <url>
    <loc>https://wiki-tale.app/</loc>
    <xhtml:link rel="alternate" hreflang="ru" href="https://wiki-tale.app/" />
    <xhtml:link rel="alternate" hreflang="en" href="https://wiki-tale.app/en" />
    <xhtml:link rel="alternate" hreflang="x-default" href="https://wiki-tale.app/" />
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://wiki-tale.app/en</loc>
    <xhtml:link rel="alternate" hreflang="ru" href="https://wiki-tale.app/" />
    <xhtml:link rel="alternate" hreflang="en" href="https://wiki-tale.app/en" />
    <xhtml:link rel="alternate" hreflang="x-default" href="https://wiki-tale.app/" />
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>${urls}
</urlset>`;

  res.setHeader('Content-Type', 'application/xml; charset=utf-8');
  res.setHeader('Cache-Control', 'public, max-age=3600'); // sitemap can be cached, unlike per-story OG pages
  res.status(200).send(xml);
};