// src/utils/SitemapGenerator.js
// Basit çok dilli sitemap üretici (TR/EN) – public/sitemap.xml yazar

import { writeFileSync, mkdirSync, existsSync } from "fs";
import { resolve } from "path";

const SITE_URL = process.env.SITE_URL || "https://cesstructure.com";
const OUT_DIR = resolve(process.cwd(), "public");
const OUT_FILE = resolve(OUT_DIR, "sitemap.xml");

// Sayfa eşleştirmeleri (TR <-> EN)
// Gerektikçe yeni rotaları buraya ekleyin
const pairs = [
  { tr: "/tr",               en: "/en",              pri: 1.0,  freq: "weekly" },
  { tr: "/tr/hakkimizda",    en: "/en/about",        pri: 0.9,  freq: "monthly" },
  { tr: "/tr/iletisim",      en: "/en/contact",      pri: 0.8,  freq: "yearly" },
  { tr: "/tr/kariyer",       en: "/en/careers",      pri: 0.7,  freq: "monthly" },
  { tr: "/tr/sss",           en: "/en/faq",          pri: 0.6,  freq: "monthly" },
  { tr: "/tr/projeler",      en: "/en/projects",     pri: 0.8,  freq: "weekly" },
];

// XML helper
const esc = (s) =>
  s.replace(/&/g, "&amp;")
   .replace(/</g, "&lt;")
   .replace(/>/g, "&gt;")
   .replace(/"/g, "&quot;")
   .replace(/'/g, "&apos;");

const lastmod = new Date().toISOString();

function urlEntry(loc, alternates, changefreq = "monthly", priority = 0.7) {
  const locAbs = `${SITE_URL}${loc}`;
  const altXml = alternates.map(a =>
    `    <xhtml:link rel="alternate" hreflang="${a.lang}" href="${SITE_URL}${a.href}"/>`
  ).join("\n");

  return `
  <url>
    <loc>${esc(locAbs)}</loc>
${altXml ? altXml + "\n" : ""}    <lastmod>${lastmod}</lastmod>
    <changefreq>${changefreq}</changefreq>
    <priority>${priority.toFixed(1)}</priority>
  </url>`;
}

function build() {
  if (!existsSync(OUT_DIR)) mkdirSync(OUT_DIR, { recursive: true });

  const urls = [];

  // Her çifti iki ayrı <url> olarak, fakat karşılıklı alternate’leriyle yaz
  for (const p of pairs) {
    urls.push(urlEntry(
      p.tr,
      [
        { lang: "tr", href: p.tr },
        { lang: "en", href: p.en },
        { lang: "x-default", href: p.tr },
      ],
      p.freq, p.pri
    ));

    urls.push(urlEntry(
      p.en,
      [
        { lang: "tr", href: p.tr },
        { lang: "en", href: p.en },
        { lang: "x-default", href: p.tr },
      ],
      p.freq, p.pri
    ));
  }

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
${urls.join("\n")}
</urlset>`;

  writeFileSync(OUT_FILE, xml, "utf8");
  console.log("✔ sitemap.xml oluşturuldu ->", OUT_FILE);
}

build();
