// /api/sitemap.js
// Live sitemap — pulls every "live" stay's slug straight from Supabase,
// so new hostels start showing up in Google without anyone editing a file.
// Uses the same public (anon/publishable) Supabase URL and key already
// visible in index.html — that key is meant to be public, so reusing it
// here is fine. If you'd rather keep it out of this file, set
// STAYKRO_URL and STAYKRO_KEY as Environment Variables in the Vercel
// dashboard instead — the code below will use those first if present.

export default async function handler(req, res) {
  const SUPABASE_URL = process.env.STAYKRO_URL || "https://ftkeuwidykexkdzogjpv.supabase.co";
  const SUPABASE_KEY = process.env.STAYKRO_KEY || "sb_publishable_nbfMjtBQtCGmvEaGvlLFRA_EOdwz32D";
  const SITE = "https://staykro.com";

  const staticPaths = [
    "", "explore", "cities",
    "city/sikar", "city/kota", "city/jaipur", "city/delhi", "city/pune", "city/indore",
    "stays/student", "stays/professional", "stays/short-term",
    "guide", "guide/judge-a-hostel", "guide/monthly-cost", "guide/hostel-or-pg",
    "about", "faq", "owners"
  ];

  let stayPaths = [];
  try {
    const r = await fetch(
      `${SUPABASE_URL}/rest/v1/stays?select=slug&status=eq.live`,
      { headers: { apikey: SUPABASE_KEY, Authorization: `Bearer ${SUPABASE_KEY}` } }
    );
    const rows = await r.json();
    if (Array.isArray(rows)) stayPaths = rows.map(row => `stay/${row.slug}`);
  } catch (e) {
    // Supabase unreachable right now — sitemap still goes out with the static pages
    // rather than failing outright.
  }

  const all = [...staticPaths, ...stayPaths];
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${all.map(p => `  <url><loc>${SITE}/${p}</loc></url>`).join("\n")}
</urlset>`;

  res.setHeader("Content-Type", "application/xml");
  res.setHeader("Cache-Control", "public, max-age=3600");
  res.status(200).send(xml);
}
