
const fs = require("fs");
const path = require("path");
const { allBlogs, allProducts } = require(path.resolve(__dirname, "../utlis/constant.utils.js"));

const BASE_URL = "https://cibusindustries.com";
const sitemapPath = path.join(__dirname, "../public/sitemap.xml");
const appDir = path.join(process.cwd(), "app");

const getCurrentDate = () => new Date().toISOString();

const cleanUrl = (url) => {
  let cleaned = url
    .replace(/\/\([^)]*\)/g, "") 
    .replace(/\/$/, "");   
  return cleaned === "" ? "/" : cleaned;
};

const getStaticPages = (dir = appDir, basePath = "") => {
  let urls = [];
  const files = fs.readdirSync(dir);

  files.forEach((file) => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      const nested = getStaticPages(filePath, `${basePath}/${file}`);
      urls = urls.concat(nested);
    } else if (file.match(/^(page)\.(js|jsx|ts|tsx)$/)) {
      urls.push(basePath || "/");
    }
  });

  return urls;
};

const buildXml = (urls) => {
  const xmlUrls = urls
    .map(({ loc, priority }) => {
      return `
<url>
  <loc>${BASE_URL}${cleanUrl(loc)}</loc>
  <lastmod>${getCurrentDate()}</lastmod>
  <priority>${priority}</priority>
</url>`;
    })
    .join("");

  return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${xmlUrls}
</urlset>`;
};

const generateSitemap = () => {
  const staticPages = getStaticPages().map((route) => ({
    loc: route,
    priority: route === "/" ? "1.0" : "0.8",
  }));

  const productPages = allProducts.map((p) => ({
    loc: `/product-details/${p.slug}`,
    priority: "0.6",
  }));

  const blogPages = allBlogs.map((b) => ({
    loc: `/news-details/${b.slug}`,
    priority: "0.6",
  }));

  const seen = new Set();
  const allUrls = [...staticPages, ...productPages, ...blogPages].filter((item) => {
    const cleaned = cleanUrl(item.loc);
    if (seen.has(cleaned)) return false;
    seen.add(cleaned);
    return true;
  });

  const sitemapXml = buildXml(allUrls);
  fs.writeFileSync(sitemapPath, sitemapXml, "utf8");

  console.log(`✅ Sitemap generated at: public/sitemap.xml`);
};

generateSitemap();
