import { MetadataRoute } from 'next'
import prisma from '@/lib/prisma'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://store.amanenime.my.id'

  // Halaman Statis
  const staticPages = [
    '',
    '/games',
    '/pterodactyl',
    '/smm',
    '/login',
    '/register',
  ].map((route) => ({
    url: `${baseUrl}${route}`,
    lastModified: new Date(),
    changeFrequency: 'daily' as const,
    priority: route === '' ? 1 : 0.8,
  }))

  // Fetch Kategori Game Aktif
  let gamePages: MetadataRoute.Sitemap = []
  try {
    const categories = await prisma.gameCategory.findMany({
      where: { isActive: true },
      select: { slug: true, updatedAt: true }
    })
    gamePages = categories.map((cat) => ({
      url: `${baseUrl}/games/${cat.slug}`,
      lastModified: cat.updatedAt,
      changeFrequency: 'weekly' as const,
      priority: 0.9,
    }))
  } catch (error) {
    console.error('Sitemap Error (Games):', error)
  }

  // Fetch Produk Digital Aktif (App Premium)
  let digitalPages: MetadataRoute.Sitemap = []
  try {
    const digitalProducts = await prisma.digitalProduct.findMany({
      where: { isActive: true },
      select: { id: true, updatedAt: true }
    })
    digitalPages = digitalProducts.map((prod) => ({
      url: `${baseUrl}/digital/${prod.id}`,
      lastModified: prod.updatedAt,
      changeFrequency: 'weekly' as const,
      priority: 0.8,
    }))
  } catch (error) {
    console.error('Sitemap Error (Digital):', error)
  }

  return [...staticPages, ...gamePages, ...digitalPages]
}
