import { NextRequest, NextResponse } from 'next/server'
import { authenticateH2H, h2hUnauthorized } from '@/lib/h2h-auth'
import prisma from '@/lib/prisma'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest) {
  const user = await authenticateH2H(req)
  if (!user) return h2hUnauthorized()

  try {
    const { searchParams } = new URL(req.url)
    const slug = searchParams.get('slug')

    if (slug) {
      const category = await prisma.gameCategory.findUnique({
        where: { slug, isActive: true },
        include: {
          products: {
            where: { isActive: true, status: true },
            select: { id: true, productName: true, sellPrice: true, description: true, server: true },
            orderBy: { sellPrice: 'asc' },
          },
        },
      })
      if (!category) return NextResponse.json({ success: false, error: 'Kategori tidak ditemukan' }, { status: 404 })
      return NextResponse.json({ success: true, data: category })
    }

    const categories = await prisma.gameCategory.findMany({
      where: { isActive: true },
      select: { id: true, name: true, slug: true, thumbnail: true },
      orderBy: { sortOrder: 'asc' },
    })

    return NextResponse.json({ success: true, data: categories })
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Gagal memuat data' }, { status: 500 })
  }
}
