import { getSitemapUrls } from "../utils/sitemap.js";

export async function sitemapHandler(req, res) {
  try {
    const { u } = req.query;
    if (!u) return res.status(400).json({ error: "Missing ?u=https://site.com" });

    const origin = new URL(String(u));
    const urls = await getSitemapUrls(origin.toString());
    res.json({
      ok: true,
      origin: origin.origin,
      count: urls.length,
      urls,
    });
  } catch (err) {
    console.error("sitemap error:", err);
    res.status(500).json({ error: "Failed to fetch sitemap", details: String(err?.message ?? err) });
  }
}
