import type { Context } from "koa";
import { Page } from "@sealcode/sealgen";

export const actionName = "Sitemap";

async function generateSitemap(ctx: Context) {
	const pages = await ctx.$app.collections.pages.list(ctx.$context).fetch();

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

	for (const page of pages.items) {
		xml += `  <url>\n   <loc>${ctx.origin.replace(/\/$/, "")}${page.get("url")}</loc>\n  </url>\n`;
	}

	xml += `</urlset>\n`;
	return xml;
}

export default new (class SitemapPage extends Page {
	async canAccess() {
		return { canAccess: true, message: "" };
	}

	async render(ctx: Context) {
		ctx.set("Content-Type", "application/xml");
		return generateSitemap(ctx);
	}
})();
