import type { GetServerSideProps } from "next";
import { env } from "~/env";
import { buildRicercaUrl } from "~/providers/RicercaProvider";
import { generateSSGHelper } from "~/server/utils/ssgHelper";

async function generateSiteMap() {
	const helper = generateSSGHelper();
	const codici = await helper.annunci.getCodici.fetch();
	const dynamicUrls = codici.map((cod) => {
		return `${env.NEXT_PUBLIC_BASE_URL}/annuncio/${cod}`;
	});
	const staticUrls = [
		env.NEXT_PUBLIC_BASE_URL,
		`${env.NEXT_PUBLIC_BASE_URL}/contatti`,
		`${env.NEXT_PUBLIC_BASE_URL}/prezzi`,
		`${env.NEXT_PUBLIC_BASE_URL}/chi-siamo`,
		`${env.NEXT_PUBLIC_BASE_URL}/proprietari`,
		`${env.NEXT_PUBLIC_BASE_URL}/guida`,
		`${env.NEXT_PUBLIC_BASE_URL}/annunci`,
		`${env.NEXT_PUBLIC_BASE_URL}${buildRicercaUrl({ tipo: "Transitorio" })}`,
		`${env.NEXT_PUBLIC_BASE_URL}${buildRicercaUrl({ comune: "Bassano del Grappa" })}`,
		`${env.NEXT_PUBLIC_BASE_URL}${buildRicercaUrl({ comune: "Bassano del Grappa", tipo: "Transitorio" })}`,
		`${env.NEXT_PUBLIC_BASE_URL}${buildRicercaUrl({ tipo: "Stabile" })}`,
		`${env.NEXT_PUBLIC_BASE_URL}${buildRicercaUrl({ comune: "Marostica" })}`,
	];

	const allUrls = [...staticUrls, ...dynamicUrls];

	return `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
      ${allUrls
				.map((url) => {
					const escapedUrl = url
						.replace(/&/g, "&amp;")
						.replace(/'/g, "&apos;")
						.replace(/"/g, "&quot;")
						.replace(/>/g, "&gt;")
						.replace(/</g, "&lt;");

					return `
            <url>
              <loc>${escapedUrl}</loc>
              <lastmod>${new Date().toISOString()}</lastmod>
              <changefreq>hourly</changefreq>
              <priority>0.7</priority>
            </url>
          `;
				})
				.join("")}
    </urlset>
  `;
}

/**
 * Pagina sitemap: /sitemap.xml
 */
export const getServerSideProps = (async (context) => {
	const sitemap = await generateSiteMap();
	context.res.setHeader("Content-Type", "text/xml");
	context.res.write(sitemap);
	context.res.end();

	return {
		props: {},
	};
}) satisfies GetServerSideProps;

// You must export a React component as the default export, but it will not be rendered.
// Its sole purpose is to allow Next.js to compile the file as a Page.
export default function Sitemap() {
	return null;
}
