import type { APIRoute } from "astro";
import { getCategoryNames, getCategories, getPublishedArticles, lastPageOf } from "../lib/articles";
import { conditionalTextResponse } from "../lib/http-cache";

export const prerender = false;

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

export const GET: APIRoute = async ({ request, site }) => {
  const origin = site ?? new URL("https://qiyouxueedu.com");
  const articles = await getPublishedArticles();
  const categories = getCategories(articles, await getCategoryNames());
  const paths = new Set<string>(["/articles/"]);
  for (let page = 2; page <= lastPageOf(articles.length); page += 1) paths.add(`/articles/page/${page}/`);
  for (const article of articles) paths.add(`/articles/${article.id}/`);
  for (const category of categories) {
    paths.add(`/articles/topic/${category.slug}/`);
    for (let page = 2; page <= lastPageOf(category.count); page += 1) paths.add(`/articles/topic/${category.slug}/page/${page}/`);
  }
  const rows = [...paths].map((pathname) => `  <url><loc>${escapeXml(new URL(pathname, origin).href)}</loc></url>`);
  const xml = [`<?xml version="1.0" encoding="UTF-8"?>`, `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`, ...rows, `</urlset>`, ""].join("\n");
  return conditionalTextResponse(request, xml, "application/xml; charset=utf-8");
};
