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

const hostname = "https://antalya.metatronnest.com"; // localhost for development
const addTrailingSlash = true; // ✅ Set this true if your Next.js uses trailingSlash: true

// Utility to format URLs based on config
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: '/', changefreq: 'daily', priority: 1.0 },
    { url: '/about-antalya-restaurant/', changefreq: 'monthly', priority: 0.5 },
    { url: '/antalya-restaurant-menu/', changefreq: 'weekly', priority: 0.6 },
    { url: '/antalya-restaurant-gallery/', changefreq: 'weekly', priority: 0.6 },
    { url: '/catering-services-ontario/', changefreq: 'weekly', priority: 0.6 },
    { url: '/book-a-table/', changefreq: 'weekly', priority: 0.6 },
    { url: '/antalya-turkish-food-blog/', changefreq: 'weekly', priority: 0.6 },
];

// ✅ Dynamic blog posts (only URLs, no extra metadata needed beyond static format)
const blogPosts = [
    { slug: '/antalya-turkish-food-blog/the-art-of-turkish-tea' },
    { slug: '/antalya-turkish-food-blog/secrets-of-charcoal-grilling/' },
    { slug: '/antalya-turkish-food-blog/a-taste-of-sweet-legacy/' },
];

const blogLinks = blogPosts.map(p => ({ url: p.slug, changefreq: 'weekly', priority: 0.6 }));

const allLinks = [...staticLinks, ...blogLinks].map(l => ({ ...l, url: formatUrl(l.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();
