import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'

export const dynamic = 'force-dynamic'

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (session?.user?.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const { searchParams } = new URL(req.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const search = searchParams.get('search') || ''
    const skip = (page - 1) * limit

    const [categories, total] = await Promise.all([
      prisma.gameCategory.findMany({
        where: search
          ? {
              OR: [
                { name: { contains: search } },
                { slug: { contains: search } },
              ],
            }
          : {},
        orderBy: { name: 'asc' },
        skip,
        take: limit,
      }),
      prisma.gameCategory.count({
        where: search
          ? {
              OR: [
                { name: { contains: search } },
                { slug: { contains: search } },
              ],
            }
          : {},
      }),
    ])

    return NextResponse.json({ categories, total, page, limit, pages: Math.ceil(total / limit) })
  } catch (error) {
    console.error('[ADMIN CATEGORIES GET]', error)
    return NextResponse.json({ error: 'Gagal memuat kategori' }, { status: 500 })
  }
}
