import getBaseUrl from '~/src/lib/utils/getBaseUrl';

// noop
const SitemapPage = () => null;

SitemapPage.getInitialProps = async ({ req, res }) => {
  if (typeof window === 'undefined') {
    const baseUrl = getBaseUrl(req);
    const toUrl = (path: string) => baseUrl + path;

    const items = [
      // static urls
      {
        url: `${baseUrl}/`,
      },
      {
        url: toUrl('/faq'),
      },
      {
        url: toUrl('/terms'),
      },
      {
        url: toUrl('/privacy'),
      },
    ];

    const lines = [
      '<?xml version="1.0" encoding="UTF-8"?>',
      '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
      ...items.map(
        ({ url }) => `<url>
  <loc>${url}</loc>
  <changefreq>daily</changefreq>
  <priority>0.5</priority>
</url>`
      ),
      '</urlset>',
    ];

    res.setHeader('Cache-Control', 's-maxage=5, stale-while-revalidate');
    res.setHeader('Content-Type', 'application/xml');
    res.statusCode = 200;
    res.end(lines.join('\n'));
  }

  return { done: true };
};

export default SitemapPage;
