import type { MetadataRoute } from 'next';
import { prisma } from '@/lib/db/client';

const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL ?? 'https://gamesji.com').replace(/\/$/, '');
const URLS_PER_SITEMAP = 40_000; // stays under Google's 50k/file limit with headroom

// Splits into multiple sitemap files as the catalog grows past one file's
// worth of URLs — this is what makes "every game" viable long-term
// instead of hitting the sitemap size limit.
export async function generateSitemaps() {
  const total = await prisma.game.count({ where: { status: 'PUBLISHED' } });
  const pages = Math.max(1, Math.ceil(total / URLS_PER_SITEMAP));
  return Array.from({ length: pages }, (_, id) => ({ id }));
}

export default async function sitemap({ id }: { id: number }): Promise<MetadataRoute.Sitemap> {
  const games = await prisma.game.findMany({
    where: { status: 'PUBLISHED' },
    orderBy: { updatedAt: 'desc' },
    skip: id * URLS_PER_SITEMAP,
    take: URLS_PER_SITEMAP,
    select: { slug: true, updatedAt: true },
  });

  const gameUrls: MetadataRoute.Sitemap = games.map((g) => ({
    url: `${SITE_URL}/games/${g.slug}`,
    lastModified: g.updatedAt,
    changeFrequency: 'weekly',
    priority: 0.7,
  }));

  // Static/section pages only belong on the first shard.
  if (id === 0) {
    gameUrls.unshift(
      { url: SITE_URL, changeFrequency: 'daily', priority: 1 },
      { url: `${SITE_URL}/games`, changeFrequency: 'daily', priority: 0.9 },
    );
  }

  return gameUrls;
}
