import config from '@payload-config';
import { getServerSideSitemap } from 'next-sitemap';
import { unstable_cache } from 'next/cache';
import { getPayload } from 'payload';

export const revalidate = 3600;

const getBlogSitemap = unstable_cache(
  async () => {
    const payload = await getPayload({ config });
    const SITE_URL =
      process.env.NEXT_PUBLIC_SERVER_URL ||
      process.env.VERCEL_PROJECT_PRODUCTION_URL ||
      'https://example.com';

    const results = await payload.find({
      collection: 'posts',
      overrideAccess: false,
      draft: false,
      depth: 0,
      limit: 1000,
      pagination: false,
      where: {
        _status: {
          equals: 'published',
        },
        postType: {
          equals: 'blog',
        },
      },
      select: {
        slug: true,
        updatedAt: true,
      },
    });

    const categories = await payload.find({
      collection: 'categories',
      limit: 1000,
      overrideAccess: true,
      select: {
        slug: true,
        updatedAt: true,
      },
    });

    const dateFallback = new Date().toISOString();

    const postSitemap = results.docs
      ? results.docs
          .filter((post) => Boolean(post?.slug))
          .map((post) => ({
            loc: `${SITE_URL}/blog/${post?.slug}`,
            lastmod: post.updatedAt || dateFallback,
          }))
      : [];

    const categorySitemap = categories.docs
      ? categories.docs
          .filter((category) => Boolean(category?.slug))
          .map((category) => ({
            loc: `${SITE_URL}/blog/c/${category?.slug}`,
            lastmod: category.updatedAt || dateFallback,
          }))
      : [];

    // Add the main /blog landing page
    const blogLanding = {
      loc: `${SITE_URL}/blog`,
      lastmod: dateFallback,
      changefreq: 'daily',
      priority: 1.0,
    };

    return [blogLanding, ...postSitemap, ...categorySitemap];
  },
  ['blog-sitemap'],
  {
    tags: ['blog-sitemap'],
  }
);

export async function GET() {
  const sitemap = await getBlogSitemap();

  return getServerSideSitemap(sitemap);
}
