import type { APIRoute } from "astro";
import { site } from "../data/site";
import { categoryToSlug, getCategories, getCategoryNames, getPublishedArticles, lastPageOf } from "../lib/articles";

export const prerender = false;

const escapeXml = (value: string) => value
  .replaceAll("&", "&amp;")
  .replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;")
  .replaceAll('"', "&quot;")
  .replaceAll("'", "&apos;");

export const GET: APIRoute = async ({ site: configuredSite }) => {
  const origin = configuredSite ?? new URL("https://www.zhiyintec.com");
  const articles = await getPublishedArticles();
  const categories = getCategories(articles, await getCategoryNames());
  const paths = new Set<string>(["/", "/about/", "/articles/", "/contact/", "/faq/", "/join/", "/methodology/", "/services/"]);
  for (const service of site.services) paths.add(`/services/${service.slug}/`);
  for (const article of articles) paths.add(`/articles/${article.id}/`);
  if (articles.length > 9) for (let page = 2; page <= lastPageOf(articles.length); page += 1) paths.add(`/articles/page/${page}/`);
  for (const category of categories) {
    paths.add(`/articles/topic/${categoryToSlug(category.name)}/`);
    for (let page = 2; page <= lastPageOf(category.count); page += 1) paths.add(`/articles/topic/${categoryToSlug(category.name)}/page/${page}/`);
  }
  const body = [...paths].map((pathname) => `  <url><loc>${escapeXml(new URL(pathname, origin).href)}</loc></url>`).join("\n");
  return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${body}\n</urlset>`, {
    headers: { "Content-Type": "application/xml; charset=utf-8", "Cache-Control": "public, max-age=3600" },
  });
};
