import type { GetServerSideProps } from 'next';

const publicRoutes = ['', '/about', '/services', '/how-it-works', '/intake', '/privacy-policy', '/terms-of-use'];

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  const forwardedProtocol = req.headers['x-forwarded-proto'];
  const protocol = typeof forwardedProtocol === 'string' ? forwardedProtocol : 'https';
  const forwardedHost = req.headers['x-forwarded-host'];
  const host = typeof forwardedHost === 'string' ? forwardedHost : req.headers.host;

  if (!host) {
    throw new Error('Host header is required to build the sitemap.');
  }

  const baseUrl = `${protocol}://${host}`;
  const urls = publicRoutes.map((route) => `<url><loc>${baseUrl}${route || '/'}</loc></url>`).join('');
  const sitemap = `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls}</urlset>`;

  res.setHeader('Content-Type', 'application/xml');
  res.write(sitemap);
  res.end();

  return { props: {} };
};

export default function Sitemap() {
  return null;
}
