import { getAllAlbumsApi } from '~/src/lib/songwhipApi/albums/getAll';
import { getAllArtistsApi } from '~/src/lib/songwhipApi/artists/getAll';
import { getAllTracksApi } from '~/src/lib/songwhipApi/tracks/getAll';
import getBaseUrl from '~/src/lib/utils/getBaseUrl';

const TTL_SECS = 60 * 5; // 5 mins

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

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

    const [allArtistsData, allAlbumsData, allTracksData] = await Promise.all([
      getAllArtistsApi({ limit: 1 }),
      getAllAlbumsApi({ limit: 1 }),
      getAllTracksApi({ limit: 1 }),
    ]);

    const lastArtistAddedAt = allArtistsData.items[0].createdAtTimestamp!;
    const lastAlbumAddedAt = allAlbumsData.items[0].createdAtTimestamp!;
    const lastTrackAddedAt = allTracksData.items[0].createdAtTimestamp!;

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>${toUrl('/sitemap.xml')}</loc>
  </sitemap>
  <sitemap>
    <loc>${toUrl('/sitemap-artists.xml')}</loc>
    <lastmod>${toFormattedDate(lastArtistAddedAt)}</lastmod>
  </sitemap>
  <sitemap>
    <loc>${toUrl('/sitemap-albums.xml')}</loc>
    <lastmod>${toFormattedDate(lastAlbumAddedAt)}</lastmod>
  </sitemap>
  <sitemap>
    <loc>${toUrl('/sitemap-tracks.xml')}</loc>
    <lastmod>${toFormattedDate(lastTrackAddedAt)}</lastmod>
  </sitemap>
 </sitemapindex>`;

    res.setHeader(
      'Cache-Control',
      `s-maxage=${TTL_SECS}, stale-while-revalidate`
    );

    res.setHeader('Content-Type', 'application/xml');
    res.statusCode = 200;

    res.end(xml);
  }

  return { done: true };
};

const toFormattedDate = (timestamp: number) => {
  const date = new Date(timestamp);

  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    '0'
  )}-${String(date.getDate()).padStart(2, '0')}`;
};

export default SitemapIndexPage;
