const fs = require("fs");
const path = require("path");
const { SitemapStream, streamToPromise } = require("sitemap");

const hostname = "https://skyandsoil.metatronnest.com";
const addTrailingSlash = true;

const shouldAddSlash = (url) => {
    if (url === "/") return false;
    if (/\.[a-z0-9]{2,6}(\?.*)?$/i.test(url)) return false;
    return true;
};

const formatUrl = (url) => {
    if (!url.startsWith("/")) url = "/" + url;
    if (addTrailingSlash && shouldAddSlash(url) && !url.endsWith("/")) return url + "/";
    if (!addTrailingSlash && url.endsWith("/") && url !== "/") return url.slice(0, -1);
    return url;
};

// ✅ Static pages
const staticLinks = [
    { url: "/" },
    { url: "/about/" },
    { url: "/projects/" },
    { url: "/residential-real-estate/" },
    { url: "/lifestyle/" },
    { url: "/contact/" },
    { url: "/compare/" },
    { url: "/privacy-policy/" },
    { url: "/terms-of-service/" },
];

// ✅ Dynamic property pages (manual slugs)
const propertyPages = [
    { slug: "/residential-real-estate/barca-at-godrej-msr-city/" },
    { slug: "/residential-real-estate/godrej-woods/" },
    { slug: "/residential-real-estate/godrej-hoskote/" },
    { slug: "/residential-real-estate/godrej-lakeside-orchard/" },
    { slug: "/residential-real-estate/godrej-tiara/" },
];

const propertyLinks = propertyPages.map(page => ({ url: page.slug }));

// Combine static + property links
const allLinks = [...staticLinks, ...propertyLinks].map(link => ({
    url: formatUrl(link.url),
}));

async function generateSitemap() {
    try {
        const sitemap = new SitemapStream({ hostname });
        const writeStream = fs.createWriteStream(path.resolve(__dirname, "../public/sitemap.xml"));

        sitemap.pipe(writeStream);

        console.log("📦 Writing URLs to sitemap:");
        allLinks.forEach(link => {
            console.log(" -", hostname + link.url);
            sitemap.write(link);
        });

        sitemap.end();
        await streamToPromise(sitemap);

        console.log("✅ sitemap.xml created successfully!");
    } catch (error) {
        console.error("❌ Error creating sitemap.xml:", error);
    }
}

generateSitemap();
